Javascript 为什么clearInterval没有';在窗口模糊和焦点事件功能中不工作?
我有一个小型通知和警报系统 我只是尝试检测窗口的状态是模糊还是聚焦,然后列出这些警报和通知。但是我的clearInterval方法不起作用。这是代码Javascript 为什么clearInterval没有';在窗口模糊和焦点事件功能中不工作?,javascript,jquery,clearinterval,Javascript,Jquery,Clearinterval,我有一个小型通知和警报系统 我只是尝试检测窗口的状态是模糊还是聚焦,然后列出这些警报和通知。但是我的clearInterval方法不起作用。这是代码 $(document).ready(function(){ setTimeout(function(){loadMessageNotifications()},600); setTimeout(function(){loadStoryNotifications()},400); var intervalStory
$(document).ready(function(){
setTimeout(function(){loadMessageNotifications()},600);
setTimeout(function(){loadStoryNotifications()},400);
var intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
var intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000);
$(window).bind("focus", function(event){
setTimeout(function(){loadMessageNotifications()},600);
setTimeout(function(){loadStoryNotifications()},400);
var intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
var intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000);
}).bind("blur", function(event){
clearInterval(intervalStoryAlerts);
clearInterval(intervalMessageAlerts);
});
});
这些clearInterval的console.log()输出未定义。这可能是因为您使用了错误的(超出范围的)
intervalStoryAlerts
和intervalMessageAlerts
,因此它们指向新的间隔。而是将重新声明放在焦点的绑定中。尝试:
// variables defined in enclosing scope
var intervalStoryAlerts = ..;
var intervalMessageAlerts = ..;
$(window).bind("focus", function(event){
setTimeout(function(){loadMessageNotifications()},600);
setTimeout(function(){loadStoryNotifications()},400);
// remove var here so that new variables are not created
intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000);
})
这使这两个变量成为函数的局部变量,并且您的代码不会覆盖ready处理程序作用域中的变量。因此,这些值将丢失,并且不会清除间隔。只需省略“
var
”谢谢您的关注。现在可以了。使用窗口解决了这个问题@pst变量已经在封闭范围内声明,只是声明了两次。这不会创建一个全局变量,只需重新初始化一个现有的变量。hi和welcome on stackoverflow。请你详细说明哪个是问题好吗?谢谢另外,请注意,可以通过删除匿名函数来简化代码:setTimeout(loadMessageNotifications,600)
,而不是setTimeout(function(){loadMessageNotifications()},600)
(等等)。如果需要将参数传递给loadMessageNotifications()
和其他函数,则只需要匿名函数。请阅读var
和变量范围(将它们用作搜索短语)。我对“不工作”给出了-1(请避免使用此短语和类似短语);使标题/问题摘要更准确地描述真正的错误/原因-这已经完成,但只在文章的最后一行。考虑这个总结/问题描述:“变量在不同回调中未定义”谢谢您的建议和答案。我用“窗口”解决了这个问题。这是代码DanieleB谢谢你的好意。我做了关于示波器的错误。当我记录ClearInterval时,我正在监视一个未定义的错误。谢谢你的-1。这真的让我进步了。此外,我还了解了示波器,谢谢。
….bind("focus", function(event){
// […]
var intervalStoryAlerts = setInterval(loadStoryAlerts, 6000);
var intervalMessageAlerts = setInterval(loadMessageAlerts, 16000);
})