Javascript ClearTimeout不起作用

时间:2016-06-22 09:05:11

标签: javascript jquery function cleartimeout

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

stop,start和reset按钮具有setTimeout功能。我想要做的是,如果点击其中一个按钮,其他两个按钮都有清晰的按钮。但不知怎的,它现​​在还没有奏效。

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);
    }
 }

1 个答案:

答案 0 :(得分:1)

从我所知道的,你的代码没有任何问题。

但我想你可能忘了从中删除一行。

protocol Entity { } class EntityCollection { static var cachedResults = [Entity]() func findById(id: Int) -> Entity? { // Search cache for entity with id from table // Return result if exists else... // Query database // If entry exists in the database append it to the cache and return it else... // Return nil } } 在5秒后创建超时,无论何时/何时单击某个东西。

这可能会造成时间问题。

以下是可能发生的情况:

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

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

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