简体   繁体   English

一段时间后运行 function 而不阻塞执行线程

[英]Running a function after a certain period of time without holding up the execution thread

I've been working on a Discord bot using Discord.js and I've run into a frustrating limitation of Javascript that I'm trying to find a workaround for.我一直在使用 Discord.js 开发 Discord 机器人,我遇到了令人沮丧的 Javascript 限制,我正在尝试寻找解决方法。

Essentially, I come to a point in my code where I want to wait a set period of time.本质上,我在我的代码中到达了一个我想等待一段时间的地方。

Currently, I have this implemented in my code as目前,我在我的代码中实现了这个

while (new Date().getTime() < targetTime)
{
    //Waiting
}

The problem is that other aspects of my code can not function while this while loop is in action.问题是我的代码的其他方面不能 function 而这个 while 循环正在运行。 For example, I have an event listener for anytime a user sends a message in Discord, but the listener does not work while the while loop is executing.例如,我有一个事件监听器,用于用户在 Discord 中发送消息的任何时候,但在 while 循环执行时监听器不起作用。

client.on('message', async message => {
     //stuff happens here
}

Any recommendations on how to get this to work?关于如何使它工作的任何建议?

That is expected behavior, the main thread is "busy" getting a current date on every thick.这是预期的行为,主线程“忙”地获取每个厚度的当前日期。 So he cannot do anything else, because js is single-threaded.所以他不能做别的,因为js是单线程的。

You can use node-schedule npm package which implements a better algorithm for observing the current date.您可以使用节点调度npm package 实现更好的算法来观察当前日期。

const date = new Date(2020, 1, 22, 12, 0, 0);

schedule.scheduleJob(date, function(){
  console.log('job is running');
});

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

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