Created
April 23, 2017 23:42
-
-
Save devsnek/df7bdadb580a26175e2041c0c4f0979b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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