简体   繁体   中英

How to abort function by timeout at JavaScript

I need to execute some function but if timeout expired I need to abort this function. I tried to use setTimeout and setImmediate. I wrote this example and used setInterval in callback for checking of working but it did't help me:

function waiter(timeout, fun) {
  var functionHandler = setImmediate(fun);
  var timeoutHandler = setTimeout(() => {
    console.log('stoped');
    clearImmediate(functionHandler);
    clearTimeout(timeoutHandler);
  }, timeout);
  fun();
}

waiter(5000, () => {
  setInterval(() => {
    console.log('work');
  }, 500);
});

After clearImmediate and clearTimeout my interval still working. How I understood that method doesn't guarantee that my function will be aborted. Does anybody have an idea how to abort function execution?

UPDATE: Yes, I know that I should call clearInterval but it's just an example for work checking. For example I should parse some big data and if it doesn't can do it by timeout I need to cancel this function execution and call something else.

You need to name your interval and clear it by its name. So your interval is no longer anonymous, but you've got a reference for it.

let counter = 10;
let newYearCountdown = setInterval( () => {
    console.log(counter);
    counter--
    if (counter === 0) {
        console.log("HAPPY NEW YEAR!!");
// here i clear interval by its name.
        clearInterval(newYearCountdown);
    }
}, 1000);

The clearXXX functions don't abort functions that are currently running, they just remove functions from the async queue, so that they never start to run. JavaScript always executes code to its completion. You cannot interrupt code that's running in the main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM