【问题标题】:Javascript ClearTimeout doesnt workJavascript ClearTimeout 不起作用
【发布时间】:2016-06-22 09:05:10
【问题描述】:

我正在为我的代码寻找解决方案。我的 clearTimeout 函数在 stop() 中不起作用;和开始();功能,有人知道如何解决这个问题吗?

停止、启动和重置按钮都具有 setTimeout 功能。我想做的是,如果单击其中一个按钮,则其他两个按钮具有cleartimeout。但不知何故,它现在不起作用。

var isTimerStarted;
var timeOutElse;
var timeOut;
var opnieuw;

function start() {
    clocktimer = setInterval("update()", 1);
    x.start();
    isTimerStarted = true;
    timeOutElse = setTimeout(function(){
        document.getElementById("scherm3").style.display = "block";
        document.getElementById("scherm2.2").style.visibility = "hidden";
    }, 8000)
}

function stop() {
    x.stop();
    clearInterval(clocktimer);
    isTimerStarted = false;
    timeOut = setTimeout(function(){
        document.getElementById("scherm4").style.visibility = "visible";
        document.getElementById("scherm2.2").style.visibility = "hidden"; 
    }, 4000)
}

function reset() {
    stop();
    x.reset();
    update();
    opnieuw = setTimeout(function(){
        document.getElementById("scherm3").style.display = "block";
        document.getElementById("scherm2.2").style.visibility = "hidden"; 
    }, 10000);    
    clearTimeout(timeOut);
    clearTimeout(timeOutElse);
    document.getElementById("buttontimer").value = "Start";
} 

setTimeout(start, 5000);

function toggleTimer(event) {
    if (isTimerStarted) {
        stop();
        event.target.value = 'Start';
        clearTimeout(opnieuw);
        clearTimeout(timeOutElse);
    } else {
        start();
        event.target.value = 'Stop';
        clearTimeout(opnieuw);
        clearTimeout(timeOut);
    }
 }

【问题讨论】:

  • 您能否详细说明它现在无法正常工作的原因?
  • 您的示例中的“x”是什么。您能否发布您的 HTML,以便我们在代码 sn-p 编辑器中查看您的问题?
  • clocktimer 是否在某处声明?它不在您的 sn-p 中。它应该像其他人一样位于顶部。
  • 我建议删除与超时/间隔没有直接关系的代码。
  • @YoannM 我的 Reset 函数中的 clearTimeout 不起作用。如果我首先单击停止/启动然后重置,则两个 settimeouts 正在运行,我只想要其中一个。

标签: javascript jquery function cleartimeout


【解决方案1】:

据我所知,您的代码没有任何问题。

但我认为您可能忘记从中删除一行。

setTimeout(start, 5000); 会在 5 秒后创建超时,无论何时/无论何时单击某个事物。

这可能会造成时间问题。

这是一个可能发生的场景:

  • 你点击
  • toggleTimer() -> start() -> 创建超时和间隔
  • 5 秒后您的 setTimeout(start, 5000) 执行并重新分配您的超时和间隔变量
  • 你重新点击
  • 最新的超时和间隔被清除,但不是第一个

为了安全起见,您可以在每个函数的开头清除在所述函数中创建的超时和间隔。

这样,您将始终清除创建的超时和间隔。

【讨论】:

  • 这不只是为了'start'功能吗?
  • 我的回答已经明确了我的想法。
  • 我将 clearTimeout 放在了 reset 函数的第一行的 reset 中,并且那个有效,谢谢!
猜你喜欢
  • 2021-08-14
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
相关资源
最近更新 更多