有没有办法通过 Onclick 按钮杀死 setInterval 循环 [英] Is there any way to kill a setInterval loop through an Onclick button

查看:24
本文介绍了有没有办法通过 Onclick 按钮杀死 setInterval 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用附加到 onClick 的 setInterval 在此函数中进行了无限循环.问题是,我无法在 onClick 中使用 clearInterval 来阻止它.我认为这是因为当我将 clearInterval 附加到 onClick 时,它会杀死特定的时间间隔,而不是完全杀死函数.有什么办法可以通过 onClick杀死所有间隔?

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?

这是我的 .js 文件和我的电话制作是

Here's my .js file and the calls I'm making are

input type="button" value="generate" onClick="generation();

input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"

input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.

推荐答案

setInterval 返回一个句柄,你需要那个句柄才能清除它

setInterval returns a handle, you need that handle so you can clear it

最简单的,在你的 html 头中为句柄创建一个 var,然后在你的 onclick 中使用 var

easiest, create a var for the handle in your html head, then in your onclick use the var

// in the head
var intervalHandle = null;

// in the onclick to set
intervalHandle = setInterval(....

// in the onclick to clear
clearInterval(intervalHandle);

http://www.w3schools.com/jsref/met_win_clearinterval.asp

这篇关于有没有办法通过 Onclick 按钮杀死 setInterval 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆