最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Closure counter inside setInterval - Stack Overflow

programmeradmin0浏览0评论

I have a function:

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

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, ....)

Share Improve this question edited Jul 19, 2018 at 14:11 techkuz asked Jul 19, 2018 at 14:01 techkuztechkuz 3,9816 gold badges40 silver badges67 bronze badges 1
  • 3 You cannot do a closure this way. setInterval is always calling the outer function in your code. You must define the closure separately. – user6713871 Commented Jul 19, 2018 at 14:04
Add a ment  | 

3 Answers 3

Reset to default 5
  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);
})();

Or, since Internet Explorer is no longer a concern for most people, dispense with the IIFE and use a block instead.

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

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

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

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

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

发布评论

评论列表(0)

  1. 暂无评论