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?

Squirrl
  • 4,909
  • 9
  • 47
  • 85

2 Answers2

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.

Christoph
  • 50,121
  • 21
  • 99
  • 128
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • using the third parameter is a bad idea, because it's not supported by all browers, use a function wrapper instead. – Christoph Nov 15 '13 at 22:44
  • Why not? Not supported on all browsers? (< IE9 ) – putvande Nov 15 '13 at 22:47
  • 3
    @putvande Sure. IE8 is (sadly) still in use. – Christoph Nov 15 '13 at 22:48
  • 1
    @Christoph — Or use the polyfill which I referenced in the answer. – Quentin Nov 15 '13 at 22:54
  • @Igal — It no longer gets security updates. Some people still insist on using it. – Quentin Jul 25 '16 at 18:17
  • Was it ever an array you needed to pass to `setTimeout` as the third parameter instead of individual arguments, i.e. `setTimeout(blankWord, t, t, ...etc);`? The [polyfill at that time](//web.archive.org/web/20140721080333/https://developer.mozilla.org/en/docs/Web/API/window.setTimeout#Callback_arguments) did expect `setTimeout(func, delay, arg1, arg2)` syntax. – Sebastian Simon Sep 25 '21 at 17:09