我有以下代码。这是我试图清除间隔,但它没有奏效。请帮助我。
$(document).ready(function(){
var intervalId;
$(window).focus(function(){
var intervalId = setInterval(function(){
console.log('working');
}, 5000);
});
$(window).blur(function(){
clearInterval(intervalId);
});
});
答案 0 :(得分:3)
请勿重新声明intervalId
,然后它将成为focus
函数的本地范围:
$(window).focus(function() {
intervalId = setInterval(function() {
console.log('working');
}, 5000);
});
考虑这一部分:
$(document).ready(function() {
var intervalId;
$(window).focus(function() {
// intervalId is not the same as the `window.intervalId`
// The scope changes.
var intervalId = setInterval(function() {
//------^^^---------- Remove this var.
});
});
});