Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - Is there any way to kill a setInterval loop through an Onclick button

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?

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...