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?
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?
Share Improve this question asked Nov 15, 2013 at 22:39 SquirrlSquirrl 4,9669 gold badges51 silver badges88 bronze badges 2-
2
setTimeout(blankWord, 5000, 'word')
? – putvande Commented Nov 15, 2013 at 22:43 - 1 Answered extensively at How can I pass a parameter to a setTimeout() callback? – Dan Dascalescu Commented Apr 17, 2015 at 7:27
2 Answers
Reset to default 8Since 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.
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.