Javascript 点击按钮后连续循环
如何在单击按钮时实现setInterval或setTimeout。我的代码吼叫不循环,我怎么能在第二次按下按钮时停止它Javascript 点击按钮后连续循环,javascript,html,setinterval,Javascript,Html,Setinterval,如何在单击按钮时实现setInterval或setTimeout。我的代码吼叫不循环,我怎么能在第二次按下按钮时停止它 <!DOCTYPE HTML> <html> <head> <script> i=0; function cycle(){ setInterval(animate(),2000); } function animate(){ alert("task");
<!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>
i=0;
功能循环(){
setInterval(animate(),2000);
}
函数animate(){
警报(“任务”);
console.log(i++);
}
#纸{
背景:#A3C45E;
宽度:200px;
高度:300px;
}
*编辑而不使用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++);
}
至:
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++);
}
在第二次单击时清除间隔:
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++);
}
更改:
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++);
}
至:
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++);
}
在第二次单击时清除间隔:
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++);
}
@DanielEuchar。我添加了一个演示。祝你好运@达尼埃鲁查。我添加了一个演示。祝你好运这将清除第二次迭代的间隔,而不是第二次单击。。。所以这里没有真正的间隔。这会在第二次迭代时清除间隔,而不是第二次单击。。。所以这里没有真正的间隔。