How to pass parameters to setTimeout and setInterval
Look at the following code:
var str = 'aaa'; var num = 2; function auto(num){ alert(num); } setTimeout('auto(num)',4000);
Writing like this can work normally, but rather than saying that this is parameter passing, it is better to say that it is a global variable used directly. Therefore, this way of writing is not necessary. In general, local variables are passed as parameters.
Modify the code:
//var str = 'aaa'; var num = 2; function test(){ var str = 'bbb'; setTimeout('auto(str)',4000); } function auto(a){ alert(a); } test();
This way of writing will report an error. If you uncomment the global declaration of str, aaa will be output, that is, the function still calls the global variable.
Look at the code below:
//var str = 'aaa'; var num = 2; function test(){ var str = 'bbb'; setTimeout('auto("str")',4000); } function auto(a){ alert(a); } test();
Pay attention to the str above. Writing this way will output "str", which means that after the timer calls the function, str is directly used as a parameter. Parameters passed like this are always strings. This is not the result we want.
To pass parameters other than strings, you can use closures, see the following code:
//var str = 'aaa'; var num = 2; function test(){ var str = 'bbb'; setTimeout(auto(str),4000); } function auto(str){ return function(){ alert(str); } } test();
The output result is ‘bbb’. If you add quotes to auto(str), an error will also be reported.
Of course, it’s also good to write like this:
var num = 2; function test(){ var str = 'bbb'; //setTimeout(auto(str),4000); setTimeout(function(){alert(str)},4000); } function auto(str){ return function(){ alert(str); } } test();
The last thing to note is that when you don’t use closures to pass parameters, the function called by the timer must be quoted. Without quotes, an error will be reported. The above situation is also suitable for setInterval();
Function calls in setTimeout and setInterval
has the following code:
var num = 2; function auto(){ alert(num); } setTimeout(auto(),4000);
In this program, you can see the pop-up warning box immediately when testing. In other words, the timer will not work if the function is referenced according to the above method.
Similarly, the above writing method for setInterval does not work properly. The program can only pop up a warning box once and then report an error.
Change the timer to
setInterval('auto()',4000); setTimeout('auto()',4000);
The program works fine.
What will it look like if you don't use auto() to call a function, but just use auto?
var str = 'aaa'; var num = 2; function auto(){ alert(num); } //setInterval(auto,4000); setTimeout(auto,4000);
Any program written in this way can work normally;
If you add quotes to auto
//setInterval('auto',4000); setTimeout('auto',4000);
Neither works properly.