Created
May 12, 2022 16:56
-
-
Save Rafat97/b1fe8d4b8d7716b09bd80c3f05f8f31b to your computer and use it in GitHub Desktop.
Revisions
-
Rafat97 created this gist
May 12, 2022 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ ```js // node ./TasinProblem.js /** * * Problem is * Forced fully stop a function after a period of time * */ const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; function defaultTimeOutAfterForceStop() { console.log("Force stop"); throw new Error("Execution Timeout"); // process.exit(1); } const execute = async ( callback, maxTimeOfExecution, afterTimeOutCallback = defaultTimeOutAfterForceStop ) => { console.log("execute"); const timeoutStart = setTimeout(afterTimeOutCallback, maxTimeOfExecution); // clear the timeout const result = await callback(); console.log(result); clearTimeout(timeoutStart); // clear the timeout return result; }; (async () => { const longRunningFunction = async () => { console.log("longRunningFunction start"); await sleep(1000); console.log("longRunningFunction end"); return 1; }; // example 1 await execute(longRunningFunction, 1000); //// example 2 // await execute(longRunningFunction, 10000, () => { // console.log("Fucked up code"); // process.exit(1); // }); })(); ```