Closure counter inside setInterval

血红的双手。 提交于 2020-05-13 07:10:29

问题


I have a function:

setInterval(function () {
        var counter = 0;
        (function() {
          counter = counter + 1;
          console.log(counter);
          })(counter)
       }, 1000)

Why does not it increment the counter? (instead, it logs 1's). How to make it log ascending numbers? (1, 2, 3, ....)


回答1:


  1. You are passing an argument to your anonymous function, but you aren't assigning that argument to a variable. You forgot to put the arguments in the function definition.
  2. You are creating new variables with every iteration instead of sharing the variable between them. You need to turn your logic inside out.

(function(closed_over_counter) {

  setInterval(function() {
    closed_over_counter++;
    console.log(closed_over_counter);
  }, 1000);

})(0);

Since you are using an IIFE instead of a function you can call multiple times, this is pretty pointless. You might as well just declare the variable inside the closure.

(function() {
  var counter = 0;
  setInterval(function() {
    counter++;
    console.log(counter);
  }, 1000);
})();



回答2:


You could use a function which returns a function as closure over counter.

setInterval(function(counter) {
    return function() {
        console.log(++counter);
    };
}(0), 1000);



回答3:


Obscured version of Nina Scholz's answer with arrow functions:

setInterval(((counter) => () => console.log(++counter))(0), 1000);


来源:https://stackoverflow.com/questions/51424638/closure-counter-inside-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!