Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active February 15, 2016 15:56
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/24c4c475bdeb59405e87 to your computer and use it in GitHub Desktop.
Save WebReflection/24c4c475bdeb59405e87 to your computer and use it in GitHub Desktop.
setTimeout and setInterval extra arguments

Every single JavaScript engine supports standard timers *

These accept one or more extra argument by specs

for(var i = 0; i < 2; i++) {
  setTimeout(function (i) {
    console.log(i);
  }, 0, i); // <== see this?
}

You don't need an inline invoked function, you don't need to bind arguments, you just pass one or more parameter once and you are done.

  • JScript (IE8 and lower) and IE9 are the only exception, all others since ever supports extra arguments, including IE10, 11, and Sparta. IE9 and 8 or lower browsers are very easy to fix in a completely unobtrusive way.
@jwlrs
Copy link

jwlrs commented Mar 2, 2015

Using i in the inner function seems confusing, would it be better as something like this?

for(var i = 0; i < 2; i++) {
  setTimeout(function (j) {
    console.log(j);
  }, 0, i); // <== see this?
}

@akrawchyk
Copy link

for(var i = 0; i < 2; i++) {
    setTimeout(function (ii) {
        console.log(ii);
    }.bind(null, i), 0);
}

This approach is easier for me to understand. Better browser support since it works in IE9, only needs a polyfill for IE8 and below. One thing to note is the changing of this context within the timed function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment