清除setInterval()问题

时间:2015-07-13 20:09:34

标签: javascript jquery

我在函数X上有setInterval,每500ms运行一次。在这个函数X中,我调用了另一个函数Y,它基本上绑定了某些div上的事件。但是,我想在下次调用函数X时解除绑定这些事件(开始“新鲜”)。我的代码似乎不起作用:

setInterval(this.board.updateBoard, 500); //called from another constructor

然后启动以下功能:

Board.prototype.updateBoard = function() {
    //I attempt to unbind ALL my divs
    var divs = this.$el.find("div");
    for(var i = 0; i < divs.length; i++) {
        $(divs[i]).unbind(); //Apparently this doesn't work?
    }

    //...some code here...
    //find appropriate $div's (multiple of them), and then calls this.beginWalking() below on each of those 
    //loop here
    this.beginWalking($div, direction + "0", direction + "1");
    //end of loop
}

//alternate between classes to give appearance of walking
Board.prototype.beginWalking = function ($div, dir0, dir1) { 
    return setInterval(function () {
        if ($div.hasClass(dir0)) {
            $div.removeClass(dir0);
            $div.addClass(dir1);
        } else {
            $div.removeClass(dir1);
            $div.addClass(dir0);            
        }
    }.bind(this), 80);
};

基本上,每500毫秒调用updateBoard。每次调用时,都会调用beginWalking来设置div上的另一个间隔。正确运行的另一个间隔的目的是每80ms添加和删除一个类。在调用下一个updateBoard之前,我似乎无法取消绑定所有内容。

任何建议都赞赏!

1 个答案:

答案 0 :(得分:2)

使用clearInterval() 编辑:$(selector).toggleClass(dir0)也可能有帮助

// In other file, use a global (no var) if you need to read it from another file:
updaterGlobal = setInterval(this.board.updateBoard, 500);

// store interval references for clearing:
var updaterLocals = [];
Board.prototype.updateBoard = function() {
    //I attempt to unbind ALL my divs
    var divs = this.$el.find("div");
    // Stop existing div timers:
    while(updaterLocals.length > 0){
      clearInterval(updaterLocals[0]);
      updaterLocals.shift(); // remove the first timer
    }

    //...some code here...
    //loop here to call the below on several $div's
    this.beginWalking($div, direction + "0", direction + "1");
    //end of loop
}

//alternate between classes to give appearance of walking
Board.prototype.beginWalking = function ($div, dir0, dir1) { 
    var interval = setInterval(function () {
        if ($div.hasClass(dir0)) {
            $div.removeClass(dir0);
            $div.addClass(dir1);
        } else {
            $div.removeClass(dir1);
            $div.addClass(dir0);            
        }
    }.bind(this), 80);
    // Save the timer:
    updaterLocals.push(interval);
    return;
};
相关问题