Last active
December 2, 2024 12:46
-
-
Save cho45/cda6bb74d3d82790663762da43298538 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 functionWithTimeout(fn, timeout) { | |
const workerCode = ` | |
self.onmessage = (event) => { | |
postMessage( (${fn.toString()}).apply(null, event.data) ); | |
}; | |
`; | |
return async function (...args) { | |
return await new Promise((resolve, reject) => { | |
const worker = new Worker(URL.createObjectURL(new Blob([workerCode], { type: "application/javascript" })), { | |
type: 'module', | |
name: 'evaluator', | |
}); | |
const timer = setTimeout(() => { | |
clearTimeout(timer); | |
worker.terminate(); | |
reject(new Error('timeout')); | |
}, timeout); | |
worker.addEventListener('message', (event) => { | |
clearTimeout(timer); | |
resolve(event.data); | |
}); | |
worker.addEventListener('error', (event) => { | |
console.log('error', event); | |
clearTimeout(timer); | |
reject(event); | |
}); | |
worker.postMessage(args); | |
}); | |
}; | |
} |
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
const func = functionWithTimeout( (foo, bar) => { | |
while(true) console.log(foo, bar); | |
return "oh"; | |
}, 100); | |
const ret = await func("hoge", "fuga"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment