9

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?

asked Nov 15, 2013 at 22:39
2

2 Answers 2

8

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.

answered Nov 15, 2013 at 22:44
Sign up to request clarification or add additional context in comments.

Comments

6

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.

answered Nov 15, 2013 at 22:43

6 Comments

using the third parameter is a bad idea, because it's not supported by all browers, use a function wrapper instead.
Why not? Not supported on all browsers? (< IE9 )
@putvande Sure. IE8 is (sadly) still in use.
@Christoph — Or use the polyfill which I referenced in the answer.
@Igal — It no longer gets security updates. Some people still insist on using it.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.