Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement