2

How do I add a timeout to Regex call in JavaScript (runtime = Browser) so it doesn't catastrophically backtrack? I only found solution for NodeJS and other languages but not for JavaScript. Does anyone know a good solution?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
mehulmpt
  • 15,861
  • 12
  • 48
  • 88

1 Answers1

4

You can spin up a web worker in the browser, and terminate it at any point. The following example demonstrates terminating a worker before it finished running everything it had:

(I am creating a worker from a blob for demonstration purposes. Also, this was done in Chrome, and may need some browser specific changes to work in other browsers such as shown in this question)

const workerScript = `
    setTimeout(function () {
   postMessage('You will see this');
    }, 1000);
    setTimeout(function () {
     postMessage('You will NOT see this');
    }, 5000);
`;

const blob = new Blob([workerScript], {type: 'application/javascript'});
const worker = new Worker(URL.createObjectURL(blob));

worker.onmessage = function(e) {
  console.log(e.data);
};

// You will only see ONE log from the worker
// if you change the timeout (ex. 6000), you will see two
setTimeout(() => {
  worker.terminate();
}, 3000);
KevBot
  • 17,900
  • 5
  • 50
  • 68