gpt4 book ai didi

javascript - 清除 setInterval() 问题

转载 作者:行者123 更新时间:2023-12-02 15:58:35 25 4
gpt4 key购买 nike

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

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

基本上,updateBoard 每 500 毫秒调用一次。每次调用时,都会调用 beginWalking 以在 div 上设置另一个间隔。这个其他间隔(其功能正常)的目的是每 80 毫秒添加和删除一个类。我似乎无法在调用下一个 updateBoard 之前取消所有内容的绑定(bind)。

任何建议表示赞赏!

最佳答案

使用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;
};

关于javascript - 清除 setInterval() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31392496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com