javascript中的计时器有时不想停止计数

Timers in javascript don't want to stop counting sometimes

本文关键字:不想 计时器 javascript      更新时间:2023-09-26

我在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);

连续两次,窗口。TimerHTML获得分配给它的新间隔。但这并不意味着之前分配给窗口的间隔。在此之前的TimerHTML已被清除。它仍然继续运行,但不再分配一个要访问的变量。

您可以通过连续运行以下两个命令来测试它

window.TimerHTML = setInterval(function(){
    console.log("A");
}, 500);
    window.TimerHTML = setInterval(function(){
    console.log("B");
}, 500);

即使你清除窗口。TimerHTML仍然会看到"A"正在登录到控制台中。这是因为之前的计时器从未被清除。并且TimerHTML不再有权访问它。

这可能是为什么你的计时器不会停止的原因。