2012-06-27 140 views
1

我怎样才能实现setInterval或setTimeout点击按钮。我的代码低吼不循环,我怎么能停止它的第二次按下按钮?连续按钮onClick按钮

<!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

回答

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

+0

哦,我就是在那里出了问题:)感谢很多gdoron –

+0

@DanielEuchar。我添加了一个演示。祝你好运! – gdoron

+0

真的不知道它已接受答案:) –

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

这将清除第二次迭代的时间间隔,而不是第二次点击......所以这里没有真正的时间间隔。 – gdoron

+0

你是对的,没有阅读正确的问题 – cuzzea