在这种情况下如何在javascript中停止setTimeout函数?

时间:2017-11-02 06:31:09

标签: javascript settimeout

我正在尝试使用js构建一个反应计时器,但每当我提前点击时,我的setTimeout doest似乎都有效。如果我没有提前点击,则不会出现问题。只需要修复earlyClick问题。请帮忙!

<!DOCTYPE html>
<html>
<head>
    <title>Reflex Calculator</title>
    <link rel="stylesheet" type="text/css" href="reflexCalculator.css">
</head>
<body>

<div id="container">

    <h1  id="seconds"></h1>
    <h2 style="text-align: center;" id="text">Click to begin.</h2>

</div>

<script type="text/javascript">

var startTime, endTime, difference;
    /*sets delay amount*/

    var randomNumberBetween2and19 = Math.floor(Math.random() * 20)+2;
    function delay1(){
        var seconds=randomNumberBetween2and19/5;
        return seconds;
    }
    var time=delay1().toFixed(3);
    /*program begins*/
    document.getElementById("container").onclick=function(){
    firstClick();}
    /*Reflex timer starts with initial color green!*/
    function firstClick(){

       document.getElementById("container").style.background="red";/*green*/
        document.getElementById("text").innerHTML="wait till blue";

这是主要问题发生的地方,但我不知道如何修复它我只想要,如果我提前点击,运行earlyClick函数并停止setTimeout

        if(document.getElementById("container").clicked) earlyClick();


        else setTimeout(calculateReflex, time*1000);
    }
    function earlyClick(){
        document.getElementById("text").innerHTML="Too Early! You have to 
        start over again.";
        document.getElementById("container").style.background="yellow";
        //document.getElementById("container").onclick=function(){start();} 
        document.getElementById("container").onclick=function()
    {lastClick();}
    }
    /*function where i use delay to calculate reflex*/
    function calculateReflex(){
        startTime=Date.now();
        document.getElementById("container").style.background="blue";
        document.getElementById("text").innerHTML="CLICK!";
        document.getElementById("container").onclick=function(){result();}      
    }
    function result(){
        endTime=Date.now();
        difference=endTime-startTime;
        document.getElementById("container").style.background="#fc3";
        document.getElementById("text").innerHTML="your reflex is 
 "+difference/1000+"s"+"<br/>Click to restart";
        document.getElementById("container").onclick=function()
 {lastClick();}
    }
    /*For reload*/
    function lastClick(){
        window.location.reload();
    }

</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

要停止setTimeout,您需要在创建超时时存储超时标识符: var timeoutId = setTimeout(...); 然后使用clearTimeout(timeoutId)在trigerred之前清除超时。

答案 1 :(得分:0)

试试这个

var myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);