Skip to content

Instantly share code, notes, and snippets.

@RinatValiullov
Last active February 16, 2019 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RinatValiullov/2678f6180160cee4c596dbf54ae8df80 to your computer and use it in GitHub Desktop.
Save RinatValiullov/2678f6180160cee4c596dbf54ae8df80 to your computer and use it in GitHub Desktop.
Classic task about for loop and setTimeout

What needs to be done to get the correct sequence of numbers from 0 to 4 inclusive?

for(var i = 0; i < 5; i++) {
    setTimeout(function() {
        console.log(i);
    }, 0)
}

Solutions:

  1. Third parameter i in setTimeout as argument for handler
for(var i = 0; i < 5; i++) {
    setTimeout(function(i) {
        console.log(i)
   }, i*1000, i)
}
  1. IIFE in setTimeout
for(var i = 0; i < 5; i++) {
    setTimeout((function(z) {
        return function() {
            console.log(z)
        }
    })(i), i * 1000)
}
  1. IIFE out of setTimeout
for(var i = 0; i < 5; i++) {
    (function(z) {
        setTimeout(function(i) {
            console.log(z)
        }, i*1000)
     })(i)
}
  1. With help of bind
for(var i = 0; i < 5; i++) {
    setTimeout((function(i) {
        console.log(i)
    }).bind(null, i), i*1000)
}
  1. ES2015 approach (block scoped variable with let keyword )
for(let i = 0; i < 5; i++) {
    setTimeout(function() {
        console.log(i)
    }, i*1000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment