You 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.