Javascript 正在清除setInterval()问题
我在每500毫秒运行一次的函数X上有一个Javascript 正在清除setInterval()问题,javascript,jquery,Javascript,Jquery,我在每500毫秒运行一次的函数X上有一个setInterval。在这个函数X中,我调用另一个函数Y,它本质上绑定了一些divs上的事件。但是,我希望在下次调用函数X时解除这些事件的绑定(以开始“刷新”)。我的代码似乎不起作用: setInterval(this.board.updateBoard, 500); //called from another constructor 然后启动以下功能: Board.prototype.updateBoard = function() { //
setInterval
。在这个函数X中,我调用另一个函数Y,它本质上绑定了一些div
s上的事件。但是,我希望在下次调用函数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);
};
Board.prototype.updateBoard=函数(){
//我试图解开我所有的带子
var divs=此$el.find(“div”);
对于(变量i=0;i
基本上,updateBoard
每500毫秒调用一次。每次调用它时,都会调用beginWalking
,以在div
上设置另一个间隔。另一个时间间隔的作用是每隔80ms添加和删除一个类,该时间间隔功能正常。在调用下一个updateBoard
之前,我似乎无法解除所有绑定
任何建议,谢谢 使用
编辑:$(选择器)。切换类(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;
};
似乎您正在将事件绑定到board类本身,而不是div。绑定事件的代码在哪里
function(){}.bind(this)
与$(“选择器”).bind()不同。你想清除间隔吗你完全正确。我在区分两者时犯了一个很大的错误。很抱歉!!!