带有计数的setInterval()

setInterval() with a count

本文关键字:setInterval      更新时间:2023-09-26

如果可能的话,我想使用来删除count并在self.addOrbitTrap()中使用一个参数。目前,为了测试我的代码,我做了这样的事情:

Bbrot.prototype.findMSet = function() {
    //...code
    var self = this;
    canvasInterval = setInterval(function() {
        self.addOrbitTrap();
    }, 0);
}
var count = 0;
Bbrot.prototype.addOrbitTrap = function() {
    //...code
    if (count === 100) {
        // Call a different function. That's why I use count
    }
    count++;
}

编辑:更具体地说,count在我的代码中用于计算addOrbitTrap()成功运行的次数(如果随机选择的像素是Mandelbrot集的一部分,则不会添加轨道陷阱)。在它运行了一些次之后,我调用了一个不同的函数(来自addOrbitTrap())。我宁愿不使用全局变量,因为count在其他任何地方都没有使用。

您可以在传递给addOrbitTrap()findMSet中引入count作为局部变量;每间隔一段时间,数值就会增加:

Bbrot.prototype.findMSet = function() {
    //...code
    var self = this,
    count = 0;
    canvasInterval = setInterval(function() {
        self.addOrbitTrap(++count);
    }, 0);
}

处理值很简单:

Bbrot.prototype.addOrbitTrap = function(count) {
    //...code
    if (count === 100) {
        // Call a different function. That's why I use count
    }
}

只需在对象上创建变量并使用它。

Bbrot.prototype.count = 0;
Bbrot.prototype.findMSet = function() {
    //...code
    var self = this;
    canvasInterval = setInterval(function() {
        self.addOrbitTrap();
    }, 0);
}
Bbrot.prototype.addOrbitTrap = function() {
   if(ranSuccessful)
      this.count++;
}
Bbrot.prototype.someOtherFunc = function() {
    return this.count;
}