[英]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.