1

如何在单击按钮时实现 setInterval 或 setTimeout。我的下面的代码没有循环,我如何在第二次按下按钮时停止它?

<!DOCTYPE HTML>
<html>
  <head>
    <script>
    i=0;
    function cycle(){
        setInterval(animate(),2000);
    }

    function animate(){
        alert("task");
        console.log(i++);
    }           
    </script>

    <style>
    #paper{
        background: #A3C45E;
        width:200px;
        height:300px;
    }
    </style>
  </head>
  <body>
    <input type="button" onClick="cycle()" value="Cycle">
    <div id="paper"></div>
  </body>
</html>

*不使用 jquery 进行编辑

4

2 回答 2

1

改变:

setInterval(animate(),2000); // calls the animate function.

至:

setInterval(animate,2000); // Pass the function as a reference for reuse.

清除第二次点击的时间间隔:

var i=0;
var id;

function cycle(){
    if (id){
        clearInterval(id);
        id = null;
    }
    else
        id = setInterval(animate, 2000);
}

function animate(){
    alert("task");
    console.log(i++);
}  

现场演示

于 2012-06-27T06:01:46.790 回答
0
var i=0;
var timer;
function cycle(){
    // this is how you pass a function to setInterval
    // setInterval returns a int representing the id of the interval
    // EDIT
    if(!timer)
      timer = setInterval(animate,2000);
    else{
      timer = false;
      clearInterval(timer)
}

function animate(){
    alert("task");
    console.log(i++);
    // clearInterval stops a interval, and you have to send as a param the id of that interval
    // EDIT
    // if(i>=1) clearInterval(timer)
}  
于 2012-06-27T06:04:57.690 回答