簡體   English   中英

如何在不使用 setTimeout() 的情況下在 x 時間后執行代碼

[英]How can I make code execute after x amount of time without using setTimeout()

這是我的情況,我的目標是在 x 時間后執行一個函數,現在setTimeout()很酷,除了在我的用例中它不可靠,我還考慮使用Date.now()並每隔第二個看看是否已經過了 x 時間,但這在我的用例中也是非常不切實際的,我願意嘗試任何建議!

我想補充一點,我的用例是從我本來可以創建的函數中設置提醒,我可以訪問鍵值數據庫,即使我的進程被終止然后重新打開,該解決方案也需要工作。

你可以做一個延遲函數並在執行下一行之前等待它

function Delay(seconds){
    return new Promise(resolve => {
         setTimeout(() => {
             resolve(true)
         }, seconds * 1000) // convert seconds to ms
    })
}

現在你可以像這樣使用它

//some code here
await Delay(5) // wait 5 seconds
// other codes here

它可能對你有幫助

function setTime(milisec){
        var startTime =new Date().getTime();
        for(var i=0; i<milisec; i++){
            if((new Date().getTime()-startTime) > milisec)
                break;
         }
         console.log('Hii I am executed');
    }
    setTime(10000000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM