连续循环单击按钮
continious loops onClick of button
如何在单击按钮时实现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)
}
相关文章:
- 如何隐藏按钮单击事件上的占位符
- 从Web服务器下载图像按钮单击使用JavaScript
- 在SweetAlert中传递ASP.NET按钮单击事件
- 单选按钮单击可刷新/更改网站的小区域
- 调用按钮单击事件 ajax 加载的用户控件
- 附加 jQuery 代码以在加载和按钮单击时运行
- 在按钮单击时将图像URL数据显示到弹出框中,而无需禁用背景
- 按钮单击服务器单击
- 触发单选按钮单击,并在页面刷新时记住选择
- 如何使用 javascript 而不是使用控制器中的方法在 rails 中呈现部分按钮单击
- jQuery UI 选项卡 - 将参数设置为下一个/上一个按钮单击
- 如何在 Angular JS 中的按钮单击上添加类
- 当元素上有多个类时触发按钮单击事件
- 如何在 HTML 中的按钮单击上更改图像(IMG URL 每次来自服务器)
- 如何使用javascript刷新我的html页面时清除按钮单击
- 阻止后退按钮 - 单击按钮时忽略
- 如何制作按钮.单击“开始时不运行”
- Rails:尝试在按钮单击时渲染部分
- 在页面加载时调用函数,在按钮单击时再次调用函数,但参数不同
- 如何在服务器端的文本中添加按钮单击事件