Last active
July 23, 2025 22:36
-
-
Save cho45/cda6bb74d3d82790663762da43298538 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export 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 blobUrl = URL.createObjectURL(new Blob([workerCode], { type: "application/javascript" })); | |
const worker = new Worker(blobUrl, { | |
type: 'module', | |
name: 'evaluator', | |
}); | |
const cleanup = () => { | |
clearTimeout(timer); | |
worker.terminate(); | |
URL.revokeObjectURL(blobUrl); | |
}; | |
const timer = setTimeout(() => { | |
cleanup(); | |
reject(new Error('timeout')); | |
}, timeout); | |
worker.addEventListener('message', (event) => { | |
cleanup(); | |
resolve(event.data); | |
}); | |
worker.addEventListener('error', (event) => { | |
console.log('error', event); | |
cleanup(); | |
reject(event); | |
}); | |
worker.postMessage(args); | |
}); | |
}; | |
} |
This file contains hidden or 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