简体   繁体   English

Javascript,切换setInterval

[英]Javascript, toggle a setInterval

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. 我正在尝试制作一个小脚本,屏幕每100毫秒随机改变它的背景颜色,你可以通过按一个按钮来打开和关闭它。 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. disco是改变背景颜色的功能。

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. 现在单击该按钮仅设置另一个间隔,尽管on变量在1和-1之间正确切换。 Am I not using clearInterval properly? 我没有正确使用clearInterval吗?

The full JSFiddle is here: http://jsfiddle.net/VZdk9/ 完整的JSFiddle在这里: http//jsfiddle.net/VZdk9/

I'm trying to practice JavaScript, so no jQuery please :) 我正在尝试练习JavaScript,所以请不要jQuery :)

You have a scope issue with your variable light since it is defined inside the change() function. 您的变量light有一个范围问题,因为它是在change()函数中定义的。 In order to keep track of the interval ID, you need to make it a global variable. 为了跟踪间隔ID,您需要使其成为全局变量。

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 . 我也删除了你的变量on因为它的可能值-11都是真的 You really only need to use one variable since light will be reset to null if the interval has been cleared. 你真的只需要使用一个变量,因为如果已经清除了间隔, light将被重置为null 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM