Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a parameter to a setTimeout() callback?

What is the difference between this:

function blankWord(){
    console.log('blank!');
    setTimeout(blankWord, 5000);
}
blankWord();

Which calls the function every 5 seconds as it should, and this:

function blankWord(t){
    console.log('blank!');
    setTimeout(blankWord, t);
}
blankWord(5000);

Which calls the function repeatedly insanely fast?

like image 394
Squirrl Avatar asked Nov 15 '13 22:11

Squirrl


2 Answers

Since you are missing the parameter in the second form you pass undefined from the second call on, which will essentially result in a timeout of 4ms (which is the browser minimum).

Use a function wrapper, to safely pass the parameters you need:

function blankWord(t){
    console.log('blank!');
    setTimeout(function(){blankWord(t)},t);
}
blankWord(5000);

Passing the parameters as third parameters knocks out older IEs, that's why you should not use this until IE8 is dead.

like image 127
Christoph Avatar answered Sep 30 '22 19:09

Christoph


The first script calls setTimeout with a second argument of 5000 every time.

The second script calls it with t. The first time that is 5000 (from blankWord(5000);). Each subsequent time it is undefined (from setTimeout(blankWord).

If you want to pass arguments, do so by passing them in an array as the third argument of setTimeout.

setTimeout(blankWord, t, [t])

See mdn for a polyfill to support older browsers that don't recognise the three argument form of the function.

like image 21
Quentin Avatar answered Sep 30 '22 18:09

Quentin