简体   繁体   English

如何在不使用 setTimeout() 的情况下在 x 时间后执行代码

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

Here's my situation, my goal is to have a function execute after x amount of time, now setTimeout() works cool for that except it unreliable in my use case, I've also considered using Date.now() and doing a check every second to see if x amount of time has passed but that's very unrealistic in my use case also, I'm willing to try any suggestions!这是我的情况,我的目标是在 x 时间后执行一个函数,现在setTimeout()很酷,除了在我的用例中它不可靠,我还考虑使用Date.now()并每隔第二个看看是否已经过了 x 时间,但这在我的用例中也是非常不切实际的,我愿意尝试任何建议!

I'd like to add that my use case is setting a reminder from a function that I would have made, I've got access to a key-value database and this solution needs to work even if my process is killed then reopened.我想补充一点,我的用例是从我本来可以创建的函数中设置提醒,我可以访问键值数据库,即使我的进程被终止然后重新打开,该解决方案也需要工作。

you can make a delay function and await it before execution of the next line你可以做一个延迟函数并在执行下一行之前等待它

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

now you can use it like this现在你可以像这样使用它

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

It may be helpful for you它可能对你有帮助

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.

相关问题 如何让 setTimeout 调用 setInterval 使其在一段时间后执行? - How to make a setTimeout to call a setInterval to make it execute after some time? 如何使文本在x时间后更改颜色 - How to make text change color after x amount of time VSCode 扩展:如何在 x 时间后自动删除错误消息? - VSCode extension: How can I remove the error message automatically after x amount of time? 如何让代码等到满足条件 x= true 时,请注意我不想使用“setTimeOut” - How can I make a code wait until condition x= true is met , note I don't want to use 'setTimeOut' 如何使用setTimeout和promises使此JS代码更具功能性? - How can I make this JS code more functional using setTimeout and promises? 如何在设定的时间后更改 MongoDB 文档中的字段? - How can I make a field in a MongoDB document change after a set amount of time? 如何使CSS代码运行一定的时间? - How do I make css code run for a certain amount of time? 如果元素在视口中停留X倍的时间,如何触发函数? - How can I trigger a function if an element is in the viewport for X amount of time? 如何在不使用 setTimeout 的情况下操作影子根? - How to can I manipulate the shadow root without using setTimeout? 如何在不使用setTimeout的情况下延迟这些动画? - How can I delay these animations without using setTimeout?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM