setInterval中的关闭计数器 [英] Closure counter inside setInterval

查看:84
本文介绍了setInterval中的关闭计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数:

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

为什么不增加计数器? (而是记录1)。如何使它记录升序数字? (1、2、3,...。)

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

推荐答案


  1. 您正在将参数传递给您的匿名函数,但您没有将该参数分配给变量。您忘记了将参数放入函数定义中。

  2. 每次迭代都在创建新变量,而不是在它们之间共享变量。您需要将逻辑从内到外。

(function(closed_over_counter) {

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

})(0);

由于您使用的是IIFE而不是可以多次调用的函数,所以这毫无意义。您最好在闭包内部声明变量。

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);
})();

这篇关于setInterval中的关闭计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆