[英]Timers in javascript don't want to stop counting sometimes
我在javascript中有3个计时器,我创建了按钮来控制它们的流程(切换它们)。 但是(仅!)有时他们不想停止。 问题出在哪里? 计时器过多? 我正在Google Chrome上进行测试。
因此,我的代码最重要的部分是:
//to insert infos
function addInfo(info){
$("#info").text(info);
clearTimeout(window.myTimer);
window.myTimer = setTimeout(function() {
$("#info").text("");
}, 5000);
return true;
}
function startHTML(){
window.TimerHTML = setInterval(function(){
//ajax
}, 500);
}
function startView(){
window.TimerView = setInterval(function(){
//ajax
}, 2000);
}
function stop_html(){
clearInterval(TimerHTML);
startView();
addInfo("html->view ");
}
function start_html(){
clearInterval(TimerView);
startHTML();
addInfo("view->html");
}
$(function() {
startView();
start_html();
//these actions should switch timers
$("#stop_html").click(function(){
stop_html();
return false;
});
$("#start_html").click(function(){
start_html();
return false;
});
});
编辑:添加了html
<button class="btn btn-primary btn-allwidth" id="start_html" data-toggle="tooltip" data-placement="right" title="View->Html">HTML ON</button> <button class="btn btn-primary btn-allwidth" id="stop_html" data-toggle="tooltip" data-placement="right" title="HTML->View">HTML OFF</button> <a href="#" onclick="javascript:$('#info-container').toggle('slow'); return false;" class="btn btn-primary btn-allwidth" data-toggle="tooltip" data-placement="right" title="Infos">Infos<i class="glyphicon glyphicon-chevron-down"></i></a> <div id="info-container"> <div id="info" class="alert alert-success"></div> </div>
如果连续执行startHTML或startView中的任何一个(即startHTML连续执行两次),则最终将创建两个间隔。
执行时
window.TimerHTML = setInterval(function(){
//ajax
}, 500);
window.TimerHTML连续两次获得新的时间间隔。 但这并不意味着先前分配给window.TimerHTML的时间间隔已清除。 它仍然继续,但是不再分配要访问的变量。
您可以通过依次运行这两个命令来对其进行测试
window.TimerHTML = setInterval(function(){
console.log("A");
}, 500);
window.TimerHTML = setInterval(function(){
console.log("B");
}, 500);
即使您清除window.TimerHTML,您仍然会在控制台中看到“ A”被记录。 这是因为以前的计时器从未清除过。 而且TimerHTML不再有权访问它。
这可能是您的计时器无法停止的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.