如何向setInterval()
提供特定的ID,然后通过ID调用clearInterval()
。
$('.notify').each(function () {
var chkr = $(this).find('span').text();
if (chkr == 'Offline') {
if (typeof(clearC) !== 'undefined') {
clearInterval(clearC);
}
// how can i provide the ID of "clearC" below
clearC = setInterval(function () {
soundOn();
}, 500);
}
else {
//how can i clear "clearC" with the ID provided in if statement
if (typeof(clearC) !== 'undefined') {
clearInterval(clearC);
}
}
});
问题是当 if
语句执行时声音继续。但是对于下一行,它在 else
语句中输入(因为“在线”)并清除间隔,尽管它不应该。
所以我关心的是清除特定行的clearInterval
,直到找到“Online”文本。
最佳答案
这种方式呢?
$('.notify').each(function() {
var $this = $(this);
var intervalID = $this.data('intervalID');
var chkr = $this.find('span').text();
clearInterval(intervalID);
if (chkr === 'Offline') {
$this.data('intervalID', setInterval(function() { soundOn(); }, 500));
}
});
P.S. 你不需要在 undefined
上检查带有区间 ID 的变量,在性能上没有真正的好处,只是不必要的代码。
关于javascript - 提供 setInterval 的 ID 并通过 ID 清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365057/