Skip to content

Instantly share code, notes, and snippets.

@Rafat97
Created May 12, 2022 16:56
Show Gist options
  • Save Rafat97/b1fe8d4b8d7716b09bd80c3f05f8f31b to your computer and use it in GitHub Desktop.
Save Rafat97/b1fe8d4b8d7716b09bd80c3f05f8f31b to your computer and use it in GitHub Desktop.
// 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);
  //   });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment