连续循环点击按钮

时间:2012-06-27 05:59:58

标签: javascript html setinterval

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

2 个答案:

答案 0 :(得分: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++);
}  

Live DEMO

答案 1 :(得分: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)
}