2

I'm quite sure with this, but just to have your opinion:

Is it somehow possible to perform operations in the background with Javascript if web workers are not available? Is there perhaps a way to "misuse" the asynchronous setTimeout() function or some other mechanisms? My goal is to read things from the localStorage, do a few transformations and send them via Ajax.

Thanks.

4 Answers 4

3

You can't run operation in background, but you can split it in small chunks, and run each next part with setTimeout. As result browser will have time to render changes and will be responsive to normal actions, while your long process will be executed as well

function iteration(){
     do_some_small_amount_of_work();
     if (!not_finished)
         scheduler.setTimeout(iteration, 1); 
}
Sign up to request clarification or add additional context in comments.

Comments

2

There is not really multithreading in Javascript, but you can run code asynchronously using setTimeout(code, 0). This queues the function for execution.

1 Comment

Okay, but this means if that code is running at a point in the future the jQuery-based UI will be blocked at that point nevertheless, right?
1

Without using web workers, what you've suggested (using setTimeout) is the only way to do it, and of course it's not really "background" at all at that point. Note that you'll need to keep the processing quite short each time you fire the "background" code, because it's not really background code at all; while your code is running, the page will be fairly unresponsive (the degree to which it's unresponsive will vary by browser, but certainly any JavaScript code on the page will have to wait for your function call to finish).

Comments

1

No, there is no way to do anything in the background in Javascript. It's strictly single threaded.

You can use setTimeout or setInterval to do the work in the foreground, but just a small part of it each time. That way the interface is still reasonably responsive as it handles events between your bursts of work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.