简体   繁体   English

清除 Javascript 间隔

[英]Clear a Javascript Interval

I am running a HTTP Request to a file and depending on the response whether it be "200" or another response a success or error function is ran.我正在对文件运行 HTTP 请求,并根据响应是“200”还是其他响应,运行成功或错误功能。 This request takes place every second.此请求每秒发生一次。

The problem I am facing is when I get lots of error responses they all run together and the last one doesn't stop eg End the interval to start a new one.我面临的问题是当我收到很多错误响应时,它们都一起运行,最后一个不会停止,例如结束间隔以开始新的。

The red light begins to flash way too fast.红灯开始闪得太快。 Can anyone help me out.谁能帮我吗。 My code is below and I have been playing with it for a few hours now but can't seem to get to the bottom of it.我的代码在下面,我已经玩了几个小时了,但似乎无法深入了解它。

var requestResponses = {

    greenLight: $('.cp_trafficLight_Light--greenDimmed'),
    redLight: $('.cp_trafficLight_Light--redDimmed'),
    greenBright: 'cp_trafficLight_Light--greenBright',
    redBright: 'cp_trafficLight_Light--redBright',

    init: function (url) {
        setInterval(function () {
            requestResponses.getResponse(url);
        }, 1000);
    },

    successResponse: function () {
        var redBright = requestResponses.redBright,
            greenBright = requestResponses.greenBright;
        requestResponses.errorCode = false;
        requestResponses.redLight.removeClass(redBright);
        requestResponses.greenLight.addClass(greenBright);
    },

    errorResponse: function () {
        requestResponses.runOnInterval();
    },

    runOnInterval: function () {
        // clearInterval(runInterval);
        var redBright = requestResponses.redBright,
            greenBright = requestResponses.greenBright,
            redLight = requestResponses.redLight;
        requestResponses.greenLight.removeClass(greenBright);
        var runInterval = setInterval(function () {
            if (requestResponses.errorCode === true) {
                redLight.toggleClass(redBright);
            }
        }, 400);
    },

    getResponse: function (serverURL) {
        $.ajax(serverURL, {
            success: function () {
                requestResponses.errorCode = false;
                requestResponses.successResponse();
            },
            error: function () {
                requestResponses.errorCode = true;
                requestResponses.errorResponse();
            },
        });
    },

    errorCode: false
}

requestResponses.init('/status');

Appreciate the help.感谢帮助。

The setInterval() method repeats itself over and over, not just one time. setInterval()方法一遍又一遍地重复,而不仅仅是一次。 Your error response handler is then invoking the routine that creates another setInterval() , and so on.然后您的错误响应处理程序调用创建另一个setInterval()的例程,依此类推。 Until you have so many processes running that you get the flashing red light issue.直到您运行的进程太多以至于出现闪烁的红灯问题。

The solution is to only invoke the logic where the setInterval() call is made once.解决方案是只调用一次setInterval()调用的逻辑。 Or, even better, use setTimeout() to call the routine.或者,更好的是,使用 setTimeout() 来调用例程。 It is run one-time and likely better for your use.它只运行一次,可能更适合您的使用。

Javascript is an event driven language. Javascript 是一种事件驱动语言。 Do not loop inifinitely to check things periodically.不要无限循环以定期检查事物。 There are places to do so but most of the time either calling a delay function (setTimeout) repeatedly when needed or using a callback would be better method.有一些地方可以这样做,但大多数情况下,要么在需要时重复调用延迟函数 (setTimeout),要么使用回调函数会是更好的方法。

Using setInterval with request, think what happens if requests start taking longer than your interval.将 setInterval 与请求一起使用,想想如果请求开始花费的时间超过您的时间间隔会发生什么。

In your case, you have two loops created with setInterval.在您的情况下,您使用 setInterval 创建了两个循环。 First one is the request which will run every 1 sec.第一个是每 1 秒运行一次的请求。 Instead of using setInterval, you can modify your code to run setTimeout only after a request finishes and do other tasks just before re-running the next request :您可以修改代码以仅在请求完成后运行 setTimeout 并在重新运行下一个请求之前执行其他任务,而不是使用 setInterval:

function runRequest(...) {
    $.ajax(serverURL, { 
       ...
       complete: function () {
           setTimeout(runRequest, 1000);
       }
       ...
    });
}

function lightsOnOff() {

    var redBright = requestResponses.redBright,
        greenBright = requestResponses.greenBright,
        redLight = requestResponses.redLight;

    requestResponses.greenLight.removeClass(greenBright);
    if (requestResponses.errorCode === true) {
        redLight.toggleClass(redBright);
    }

}
setInterval(lightsOnOff, 400);

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

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