gtryonp
gtryonp

Reputation: 407

Avoid chrome "pages unresponsive" upon javascript long execution

I have a javascript LONG execution procedure (and reasons to have it). How can I avoid in javascript the message on the client machines? I read something about --disable-hang-monitor, but is a command line argument or setting, not javascript (also, I read isnt working allways)

Upvotes: 4

Views: 7127

Answers (1)

Markus
Markus

Reputation: 1636

Assuming you are doing complex calculations that can't be broken down in smaller chunks, web workers seem to the solution to me. It's the javascript mechanism to run code in a separate thread, but you have to communicate with that thread (called a worker) via messaging: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

var myWorker = new Worker('worker.js');
first.onchange = function() {
  myWorker.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

second.onchange = function() {
  myWorker.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

myWorker.onmessage = function(e) {
  result.textContent = e.data;
  console.log('Message received from worker');
}

In the worker:

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);
}

Upvotes: 5

Related Questions