codemonkey
codemonkey

Reputation: 7905

How to call clearTimeout and still run the setTimeout's function?

Here is my code:

let delayTimeout = null;
const delayExecution = mls => {
    console.log('Delaying for', mls);
    return new Promise(resolve => {
        delayTimeout = setTimeout(() => resolve('ok'), mls);
    })
}

const main = async () => {
    axios.post('URL', {data})
             .then(response => {
                 if(response passes some condition){
                     clearTimeout(delayTimeout);
                 }
             })

   const res = await delayExecution(30000)
   console.log("DONE!")
}

main();

After the axios call, I may want to terminate the delayExecution by clearing the timeout inside it. How do I clearTimeout inside my delayExecution function but still resolve the Promise?

In essence, I'm trying to finish delayExecution before its time, but still resolve the promise inside it.

Upvotes: 1

Views: 1891

Answers (4)

Thales Kenne
Thales Kenne

Reputation: 2932

Based on your edit, I'll just leave another response. Note that I haven't tested it, my mind is currently focused on my code I'm writing alongside this hehe

let delayTimeout = null;
let resolveHandler = null;
const delayExecution = mls => {
    console.log('Delaying for', mls);
    return new Promise(resolve => {
        resolveHandler = resolve;
        delayTimeout = setTimeout(() => resolve('ok'), mls);
    })
}

const main = async () => {
    axios.post('URL', {data})
             .then(response => {
                 if(response passes some condition){
                     resolveHandler('ok');
                     clearTimeout(delayTimeout);
                 }
             })

   const res = await delayExecution(30000)
   console.log("DONE!")
}

main();

The idea is just to assign the resolve function to another auxiliary variable which you can then use elsewhere :)

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22265

I have imagined that :

const runOnDelay = function( fct, delay )
        {
        let obj    = {}
          , isDone = false
          , refTim = setTimeout(()=>
              {
              isDone = true
              fct()
              }, delay)
          ;
        obj.stop = () =>
          { 
          clearTimeout(refTim)
          if (!isDone)
            fct()
          isDone = true
          }
        return obj
        }

usage:

const doneFunc = () => console.log('Finished job')

let myBoy = runOnDelay(doneFunc, 1000)

 //...

myBoy.stop()

Upvotes: 1

Thales Kenne
Thales Kenne

Reputation: 2932

If you want to run the function independently from the timeout, just declare the function outside of it, then call it whenever you want. You have most of the code done

const doneFunc = () => console.log('Finished job');

const f = setTimeout(() => doneFunc(), 10000);

/* Seome logic here */

if (condition to run before timeout) {
  clearTimeout(f);
 doneFunc();

}

/* end of logic */

Upvotes: 1

imvain2
imvain2

Reputation: 15847

doneFunc should have the clearTimeout within it, so after the function is complete the timeout is cleared.

Also, for the first setTimeout parameter, you can just pass the name of the function.

Actually for timeout, you don't need the clearTimeout since it will only be ran ONCE compared to interval which is continuing run.

const doneFunc = () => {console.log('Finished job');clearTimeout(f);}

const f = setTimeout(doneFunc, 100);

Upvotes: 1

Related Questions