Passing and calling setTimeout and setInterval functions in JavaScript

  • 2021-01-25 07:11:15
  • OfStack

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); 

This should work, but if you are talking about passing arguments, you are more likely to be using global variables directly. Therefore, this kind of writing is not necessary, 1 is more often used to pass local variables as parameters.

Change the code 1:


//var str = 'aaa'; 
var num = 2; 
function test(){ 
  var str = 'bbb'; 
  setTimeout('auto(str)',4000); 
} 
function auto(a){ 
  alert(a); 
} 
test(); 

If we uncomment the global declaration of str, we will print aaa, meaning that the function is still calling the global variable.
Look at the following code:


//var str = 'aaa'; 
var num = 2; 
function test(){ 
  var str = 'bbb'; 
  setTimeout('auto("str")',4000); 
} 
function auto(a){ 
  alert(a); 
} 
test(); 

This will output "str". This means that the timer calls the function using str as an argument. The argument passed in this way is always a string. That's not what we want.

To pass an argument that is not unexpected to a string, you can use a closure. 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 is' bbb'. Entering quotation marks around auto(str) also results in an error.
Of course, it's also good to write:


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(); 

Finally, note that when the word is passed without a closure, the timer calls the function in quotes. Without quotes, an error is reported. The above cases also apply to setInterval();


Function calls in setTimeout, setInterval
There is the following code:


var num = 2; 
function auto(){ 
  alert(num); 
} 
setTimeout(auto(),4000); 

In this program, you can immediately see a pop-up warning box when testing. In other words, the timer does not work when referring to the function as described above.

Similarly, for setInterval above the writing method can not work properly, the program can only pop up 1 warning box, and then report error.
Change the timer to


setInterval('auto()',4000); 
setTimeout('auto()',4000); 

The program works just fine.


What happens when a function is called using only auto instead of auto()?


var str = 'aaa'; 
var num = 2; 
function auto(){ 
  alert(num); 
} 
//setInterval(auto,4000); 
setTimeout(auto,4000); 

You can write a program like this;

If I put auto in quotes


//setInterval('auto',4000); 
setTimeout('auto',4000); 

They don't work properly.


Related articles: