简体   繁体   English

如何调用 clearTimeout 并仍然运行 setTimeout 的 function?

[英]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.在 axios 调用之后,我可能想通过清除其中的超时来终止delayExecution How do I clearTimeout inside my delayExecution function but still resolve the Promise?如何在我的delayExecution function 中清除超时但仍然解析 Promise?

In essence, I'm trying to finish delayExecution before its time, but still resolve the promise inside it.本质上,我试图在它的时间之前完成delayExecution ,但仍然解析其中的 promise。

doneFunc should have the clearTimeout within it, so after the function is complete the timeout is cleared. doneFunc 中应该有 clearTimeout,所以在 function 完成后超时被清除。

Also, for the first setTimeout parameter, you can just pass the name of the function.此外,对于第一个 setTimeout 参数,您可以只传递 function 的名称。

Actually for timeout, you don't need the clearTimeout since it will only be ran ONCE compared to interval which is continuing run.实际上对于超时,您不需要 clearTimeout,因为与持续运行的间隔相比,它只会运行一次。

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

If you want to run the function independently from the timeout, just declare the function outside of it, then call it whenever you want.如果您想独立于超时运行 function,只需在其外部声明 function,然后随时调用它。 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 */

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()

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:)这个想法只是将解析 function 分配给另一个辅助变量,然后您可以在其他地方使用它:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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