Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Can't stop the setTimeout

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.

Thank you Stack Overflow Community!

like image 705
Ben Avatar asked Jul 05 '26 13:07

Ben


2 Answers

There are 2 major problems with your code:

  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.

Updated functions:

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]);
    }
}

Example of use:

var timeouts = check();

// do some other stuff...

stopcheck(timeouts);
like image 72
Jordan Ryan Moore Avatar answered Jul 08 '26 02:07

Jordan Ryan Moore


Where is 't' being defined? It keeps being redefined in the for loop, so you will loose track of each timeout handle...

You could keep an array of handles:

var aTimeoutHandles = new Array();
var iCount = 0;
for (proxy in proxys) {

    var proxytimeout = proxy*5000;

    aTimeoutHandles[iCount++] = setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

}
like image 24
Robert Avatar answered Jul 08 '26 02:07

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!