set time out not working with function

前端 未结 4 1795
予麋鹿
予麋鹿 2021-01-20 03:23

I am using the following to pause the javascript for a few seconds:

 setTimeout(start_countdown(),3000);

It does not work, the function is

相关标签:
4条回答
  • 2021-01-20 03:53

    If you dont need to pass params dont use ()

    setTimeout(start_countdown,3000);
    

    If you do you have to wrap your function

    setTimeout(function(){start_countdown(parameter)},3000);
    
    0 讨论(0)
  • 2021-01-20 04:07

    You need to pass a function reference. You are passing a function's return value.

    The difference is this: one is a blueprint of the function you want to happen, the other means you are executing the function immediately and passing its return value to setTimeout.

    setTimeout(start_countdown, 3000);
    

    If you want to do something more complex than simply call a named function, OR you want to pass a param to the named function, you'll need to instead pass an anonymous function to the timeout and call your function within that:

    setTimeout(function() {
        start_countdown(/* possible params */);
        /* other code here as required */
    }, 3000);
    
    0 讨论(0)
  • 2021-01-20 04:11

    In different browsers it works in different way. In IE you need to use the anonymous function to pass the parameters to the callback:

    setTimeout(function(){alert('hi')},3000);

    0 讨论(0)
  • 2021-01-20 04:13

    write instead

    setTimeout(start_countdown, 3000);
    

    without parens ()
    the second example could be also written as

    setTimeout(function() { alert('hi'); }, 3000);
    
    0 讨论(0)
提交回复
热议问题