我在jQuery队列中有一个自定义的动画效果任务。它内部有一个setInterval调用。
一段时间后,将调用stop()函数。它从队列中移除当前正在执行的任务的回调,并开始执行下一个任务。
但是来自先前效果(已经被移除)的setInterval仍在运行。取消调用stop()的任务后,需要调用的clearInterval应该放在哪里
下面是一个示例:
$('body')
.queue(function(next) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
}, 1500);发布于 2017-08-03 06:51:09
将interval变量实例化移到队列闭包函数之外,然后可以在每次调用stop()时将其清除。
var interval = null;
$('body')
.queue(function(next) {
var i = 0, el = this;
interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
interval = null;
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
if (interval != null) {
clearInterval(interval);
interval = null;
}
}, 1500);发布于 2017-08-03 10:23:39
不确定官方是否支持这种方法,但在阅读了jQuery源代码后,我似乎找到了解决方案。给队列任务的回调函数提供了一个未记录的第二个参数。这是当前效果钩子的对象。我们需要的属性相应地命名为stop。如果设置,则仅当通过stop()或finish()方法手动停止效果时才调用闭包。在清除或设置新队列时未调用它。
下面是一个示例:
$('body')
.queue(function(next, hooks) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
hooks.stop = function() {
clearInterval(interval);
}
})
.queue(function(next) {
this.style.backgroundColor = '#005';
next();
});
setTimeout(function() {
$('body').stop();
}, 1500);https://stackoverflow.com/questions/45472118
复制相似问题