Javascript: cannot stop setTimeout

I am working on a proxy checker and have the following code to run requests at intervals of approximately 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 not stop them after they start!

        function stopcheck() {

            clearTimeout(t);

        }

A corrected or better method will be more appreciated.

Thank qaru community

+2
source share
6 answers

There are two main problems in your code:

  • t is overwritten for each timeout, losing the link to the previous timeout for each iteration.
  • tcannot be a global variable, therefore it stopcheck()may not be able to "see" t.

Updated features:

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

Usage example:

var timeouts = check();

// do some other stuff...

stopcheck(timeouts);
+6
source

't'? for, -...

:

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

    var proxytimeout = proxy*5000;

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

}
+3

t . , t for. , , , , clearTimeout .

+2

t , . , .

0

:

  • , t for; t .
  • for..in . , for..in ( , ; . ). for..in , , . for.
  • proxys . , ...
  • proxy ( , ).

, .

0

It looks like you are setting several timeouts (one for each proxy server), but trying to save them in the same variable. You probably need to use an array instead of a simple variable.

0
source

Source: https://habr.com/ru/post/1743265/


All Articles