mehulmpt
mehulmpt

Reputation: 16587

Timing out regex to avoid catastrophic backtracking

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?

Upvotes: 2

Views: 595

Answers (1)

KevBot
KevBot

Reputation: 18908

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

Upvotes: 4

Related Questions