Skip to content

Instantly share code, notes, and snippets.

@devsnek
Created April 23, 2017 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devsnek/df7bdadb580a26175e2041c0c4f0979b to your computer and use it in GitHub Desktop.
Save devsnek/df7bdadb580a26175e2041c0c4f0979b to your computer and use it in GitHub Desktop.
function makeWorker() {
return new Worker(URL.createObjectURL(new Blob([
`onmessage = function(message) {
const data = message.data;
postMessage({ status: 1 });
postMessage({ result: eval.call(this, data.code), status: 2 });
}`], { type: 'text/javascript' })));
}
function timedEval(code, timeout = 1000) {
return new Promise((resolve, reject) => {
const worker = makeWorker();
worker.onmessage = function(message) {
const data = message.data;
if (data.status === 1) {
setTimeout(() => {
worker.terminate();
reject(new Error('Script evaluation took too long!'));
}, timeout);
} else if (data.status === 2) {
resolve(data.result);
}
};
worker.postMessage({ code, status: 0 });
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment