search

Home  >  Q&A  >  body text

javascript - Solve the problem of closure and output it

for (var i = 1; i <= 10; i++) {
  setTimeout({
    console.log(i);
  },2000*i);
}

I would like to ask how to use closure to solve the problem. It outputs 1 in the first second and 2 in the second second. . . And so on?

迷茫迷茫2811 days ago779

reply all(1)I'll reply

  • typecho

    typecho2017-06-12 09:34:59

    Your js is so wrong

    for(var i=1;i<=10;i++){
      (function(i){
        setTimeout(function(){
          console.log(i);
        },1000*i)
      })(i)
    }

    reply
    0
  • Cancelreply