jordan koskei
jordan koskei

Reputation: 2789

Detect running javascript workers

I am writing a javascript HTML5 phonegap application. I am using SQLite to store data. For the sake of performance, i am undertaking database inserts asynchronously i.e. I do not need to call the next operation at the callback of the previous Database operation. Internally, i believe javascript is creating a worker for each operation hence multi-threading so to speak.

The problem now is , How do i know that all workers have completed their tasks? e.g, in order to tell the user that all data has been saved?

Upvotes: 0

Views: 371

Answers (1)

Al Crowley
Al Crowley

Reputation: 1264

If I understand your request correctly, you are queueing up DB inserts to run asynchronously and you want to be able to check back at a later time to see if all the requests are finished. I would do something like this:

function asyncTask() {
        //
        // Do real work here
        //
        runningTasks--
}


//in your init section, setup a global variable to track number of tasks    
runningTasks = 0

//when you need to create a new task, increment the counter
runningTasks++;
setTimeout (asyncTask,1);



if (runningTasks > 0) {
    //something still running
} else {
    //all tasks are done.
}

In another language you would need to worry about race conditions when testing and setting the runningTasks varaible, but AFAIK, Javascript is only implemented as single threaded so you don't need to worry about that.

Upvotes: 1

Related Questions