gpt4 book ai didi

javascript - clearInterval()不工作javascript

转载 作者:行者123 更新时间:2023-11-30 12:08:24 24 4
gpt4 key购买 nike

我有以下代码。这是我试图清除间隔的方法,但是没有用。请帮助我。

$(document).ready(function(){
var intervalId;
$(window).focus(function(){
var intervalId = setInterval(function(){
console.log('working');
}, 5000);
});

$(window).blur(function(){
clearInterval(intervalId);
});
});

最佳答案

不要重新声明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.
});
});
});

关于javascript - clearInterval()不工作javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546224/

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