Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a JavaScript setTimeout has fired

I'd like to be able to dispatch a bunch of work via JavaScript to be done in the browser in such a way that the browser stays responsive throughout.

The approach I'm trying to take is to chunk up the work, passing each chunk to a function that is then queued with a setTimeout(func, 0) call.

I need to know when all the work is done, so I'm storing the returned timer ID in a map (id -> true|false). This mapping is set to false in the next block of code after I have the timer ID, and the queued function sets the mapping to true when it completes... except, of course, the queued function doesn't know its timer ID.

Maybe there's a better/easier way... or some advice on how I can manipulate my map as I need to?

like image 611
brabster Avatar asked Nov 24 '25 23:11

brabster


2 Answers

I would queue the work in an array, use one timeout to process the queue and call a callback once the queue is empty. Something like:

var work = [...];

var run = function(work, callback) {
    setTimeout(function() {
        if(work.length > 0) {
            process(work.shift());
            setTimeout(arguments.callee, 25);
        }
        else {
            callback();
        }
    }, 25);
};

run(work, function() {
    alert('Work is done!');
});

As JavaScript in browsers is single threaded there is no real advantage to run multiple timeouts (at least I think this is what you are doing). It may even slow down the browser.

like image 99
Felix Kling Avatar answered Nov 27 '25 11:11

Felix Kling


I'd like to add that although javascript is single threaded you can still have multiple ajax calls going at once. I recently had a site that needed to do potentially hundreds of ajax calls and the browser just couldn't handle it. I created a queue that used setTimeOut to run 5 calls at once. When one of the ajax calls returned it fired a callback (which is handled by a single thread) and then made the next call on the stack.

Imagine you're a manager that can only talk to one person at a time, you give 5 employees assignments, then wait for their responses, which may come in any order. Once the first employee comes back and gives you the information, you give them a new assignment and wait for the next employee (or perhaps even the same employee) to come back. So although you're "single threaded" 5 things are going on at once.

like image 40
Jeff Cutler Avatar answered Nov 27 '25 13:11

Jeff Cutler



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!