Javascript:无法停止setTimeout [英] Javascript: Can't stop the setTimeout

查看:123
本文介绍了Javascript:无法停止setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用代理服务器检查器,并使用以下代码使用setTimeout函数以大约5秒的间隔启动请求;

I'm working on a proxy server checker and have the following code to start the requests at intervals of roughly 5 seconds using the setTimeout function;

        function check() {

            var url = document.getElementById('url').value;
            var proxys = document.getElementById('proxys').value.replace(/\n/g,',');

            var proxys = proxys.split(",");

            for (proxy in proxys) {

                var proxytimeout = proxy*5000;

                t = setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

            }
        }

但是,一旦启动,我就无法阻止他们!

However I can't stop them once their started!

        function stopcheck() {

            clearTimeout(t);

        }

修复或更好的方法将不胜感激.

A fix or better method will be more that appreciated.

感谢Stack Overflow社区!

Thank you Stack Overflow Community!

推荐答案

您的代码有2个主要问题:

There are 2 major problems with your code:

  1. t对于每个超时都会被覆盖,从而在每次迭代时都丢失对上一个超时的引用.
  2. t可能不是全局变量,因此stopcheck()可能无法看到" t.
  1. t is overwritten for each timeout, losing the reference to the previous timeout each iteration.
  2. t is may not be a global variable, thus stopcheck() might not be able to "see" t.

更新的功能:

function check() {
    var url         = document.getElementById('url').value;
    var proxys      = document.getElementById('proxys').value.replace(/\n/g,',');
    var timeouts    = [];
    var index;
    var proxytimeout;

    proxys = proxys.split(",");
    for (index = 0; index < proxys.length; ++index) {
        proxytimeout                = index * 5000;
        timeouts[timeouts.length]   = setTimeout(
            doRequest, proxytimeout, url, proxys[index];
        );
    }

    return timeouts;
}

function stopcheck(timeouts) {
    for (var i = 0; i < timeouts.length; i++) {        
        clearTimeout(timeouts[i]);
    }
}

使用示例:

var timeouts = check();

// do some other stuff...

stopcheck(timeouts);

这篇关于Javascript:无法停止setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆