Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 2 'threads' in javascript

If I have an ajax call off fetching (with a callback) and then some other code running in the meantime. How can I have a third function that will be called when both of the first 2 are done. I'm sure it is easy with polling (setTimeout and then check some variables) but I'd rather a callback.

Is it possible?

like image 267
Paul Tarjan Avatar asked May 30 '09 11:05

Paul Tarjan


People also ask

Can you multi thread JavaScript?

Multithreading in JavaScript is the real right now. You can offload your work into multiple threads and share memory between them.

What are threads in JavaScript?

Each unit capable of executing code is called a thread. The main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app.

Is JavaScript single threaded or multi thread?

JavaScript is a single-threaded language because while running code on a single thread, it can be really easy to implement as we don't have to deal with the complicated scenarios that arise in the multi-threaded environment like deadlock. Since, JavaScript is a single-threaded language, it is synchronous in nature.

How many types of threads are there in JavaScript?

js uses two kinds of threads: a main thread handled by the event loop and several auxiliary threads in the worker pool. The event loop is the mechanism that takes callbacks (functions) and registers them to be executed at some point in the future. It operates in the same thread as the proper JavaScript code.


2 Answers

You could just give the same callback to both your AJAX call and your other code running in the meantime, use a variable to track their combined progress, then link them to a callback like below:

// Each time you start a call, increment this by one
var counter = 0;

var callback = function() {
    counter--;
    if (counter == 0) {
        // Execute code you wanted to do once both threads are finished.
    }
}
like image 66
Dan Lew Avatar answered Oct 22 '22 09:10

Dan Lew


Daniel's solution is the proper one. I took it and added some extra code so you don't have to think too much ;)

function createNotifier() {
    var counter = 2;
    return function() {
        if (--counter == 0) {
            // do stuff
        }
    };
}

var notify = createNotifier();
var later = function() {
    var done = false;
    // do stuff and set done to true if you're done
    if (done) {
        notify();
    }
};

function doAjaxCall(notify) {
    var ajaxCallback = function() {
        // Respond to the AJAX callback here
        // Notify that the Ajax callback is done
        notify();
    };
    // Here you perform the AJAX call action
}

setInterval(later, 200);
doAjaxCall(notify);
like image 24
Helgi Avatar answered Oct 22 '22 09:10

Helgi