连续循环单击按钮

continious loops onClick of button

本文关键字:按钮 单击 循环 连续      更新时间:2023-09-26

如何在单击按钮时实现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进行编辑

更改:

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

现场演示

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