setTimeout js函数只工作一次

时间:2014-08-17 18:27:18

标签: javascript

setTimeout()函数只运行一次。它应该每100ms刷新一次。但是youtube教程使用了setTimeout。为什么不在我的工作?是否无法将setTimeout用于此应用程序

<html>
<head>
    <title>Stop Watch</title>

<script type="text/javascript">
var time=0;
var running=1;


function run(){
    if(running==1){
        setTimeout(function(){
            time++;
            document.getElementById("lead").innerHTML="Time: "+time;
        },100);

    }
}
</script>
</head>
<body>
    <p id="lead">Click to start Timer</p>
<button id="startPause" onclick="run()">Start</button>
<button id="reset" onclick="">Reset</button>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

setTimeOut替换为setInterval以执行重复性任务。

function run(){
    if(running==1){
        window.setInterval(function(){
            time++;
            document.getElementById("lead").innerHTML="Time: "+time;
            //run();
        },1000);

    }
    else {
        time=0;
        window.clearInterval(interval);
    }
}