Bhavna
Bhavna

Reputation: 856

executing Javascript code in background thread

Hiii everyone, I have created a tab based application using html, and I have used setInterval for synchronizing app data from the server, after regular interval of time. But the problem is that, while synchronizing the data, if i switch between tabs, the executing code is stopped and hence sync cannot be completed.

I thought of calling the sync() in different thread, but couldn't get any help on this. Any ideas about how to implement this, so that while switching between tabs, my JS code keeps on executing. Rough structure of my JS code is

setInterval(
sync();
,3000);

function sync()
{
// Code for sync data
}

Upvotes: 1

Views: 1769

Answers (2)

Fenton
Fenton

Reputation: 251242

One of the problems with your example is that you only execute sync a single time (because you added () to it within the setInterval call). Essentially you execute sync once and pass the result in.

Another problem is the ;, which terminates the line.

So removing the brackets and the semi-colon may solve your issue:

setInterval(sync, 3000);

Athough I propose you use a timeout, rather than an interval - in case the request takes longer than three seconds.

function sync() {
    // Code for sync data

    setTimeout(sync, 3000);
}

sync();

On the whole, your JavaScript executes on a single thread using an event loop to execute all of the events in order. Threading won't solve your issue anyway, as it is a slight syntax problem.

Web workers will allow additional threads in browsers and NodeJS also has a threading mechanism - but they should be used sparingly.

Upvotes: 4

000
000

Reputation: 27247

You may want to use Web Workers

The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null).

You may communicate with a web worker via messages. As an idea, you could spawn a single worker when the page starts, then send it a message with data to upload. It'll silently do it in the background for you.


Another idea is to use Web Sockets. Your browser can listen for incoming messages from a server. The server can broadcast updates to your browser.

Upvotes: 0

Related Questions