admin管理员组文章数量:1321810
I'm trying to make a small script where the screen will randomly change it's background color every 100ms, and you can toggle this on and off by pressing a single button. I can get it to start, but I can't get it to stop.
Here is the main code for toggling:
var on = -1;
function change() {
on = on*-1;
if (on == true) {
var light = window.setInterval(disco,100);
}
else {
window.clearInterval(light);
}
}
disco
is the function that changes the background color.
I've tried many different variations of this, but I think this is the closest I've gotten. Clicking the button now only set's another interval, despite the on
variable correctly switching between 1 and -1. Am I not using clearInterval properly?
The full JSFiddle is here: /
I'm trying to practice JavaScript, so no jQuery please :)
I'm trying to make a small script where the screen will randomly change it's background color every 100ms, and you can toggle this on and off by pressing a single button. I can get it to start, but I can't get it to stop.
Here is the main code for toggling:
var on = -1;
function change() {
on = on*-1;
if (on == true) {
var light = window.setInterval(disco,100);
}
else {
window.clearInterval(light);
}
}
disco
is the function that changes the background color.
I've tried many different variations of this, but I think this is the closest I've gotten. Clicking the button now only set's another interval, despite the on
variable correctly switching between 1 and -1. Am I not using clearInterval properly?
The full JSFiddle is here: http://jsfiddle.net/VZdk9/
I'm trying to practice JavaScript, so no jQuery please :)
Share Improve this question asked Feb 7, 2014 at 22:11 damondamon 2,8978 gold badges28 silver badges35 bronze badges 1 |2 Answers
Reset to default 11You have a scope issue with your variable light
since it is defined inside the change()
function. In order to keep track of the interval ID, you need to make it a global variable.
var light;
function change() {
if (!light) {
light = window.setInterval(disco,100);
} else {
window.clearInterval(light);
light = null;
}
}
I also removed your variable on
since its possible values -1
and 1
are both truthy. You really only need to use one variable since light
will be reset to null
if the interval has been cleared. If this variable is controlled by another function feel free to change it back.
var light = null;
function change () {
if (light === null) {
light = window.setInterval(disco, 100);
} else {
window.clearInterval(light);
light = null;
}
}
本文标签: javascripttoggle a setIntervalStack Overflow
版权声明:本文标题:Javascript, toggle a setInterval - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739460845a2164136.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
var light;
outside of the function, else it will be "undefined" when its called a second time for the close action . – Carl Commented Feb 7, 2014 at 22:18