Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  162] [ 4]  / answers: 1 / hits: 16178  / 9 Years ago, wed, july 15, 2015, 12:00:00

I have a long running for-loop in my code and I'd like to delay to loop to handle other tasks in the event queue (like a button press). Does javascript or JQuery have anything that could help me? Basically I'm trying to do something similar to delaying loops like here (https://support.microsoft.com/en-us/kb/118468).


More From » jquery

 Answers
132

If your application really requires long-running JavaScript code, one of the best ways to deal with it is by using JavaScript web workers. JavaScript code normally runs on the foreground thread, but by creating a web worker you can effectively keep a long-running process on a background thread, and your UI thread will be free to respond to user input.



As an example, you create a new worker like this:



var myWorker = new Worker(worker.js);


You can then post messages to it from the js in the main page like this:



myWorker.postMessage([first.value,second.value]);
console.log('Message posted to worker');


And respond to the messages in worker.js like this:



onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
console.log('Posting message back to main script');
postMessage(workerResult);
}

[#65794] Monday, July 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;