Discord.js 计时器,定期更新倒计时 [英] Discord.js timer with periodically updating countdown

查看:15
本文介绍了Discord.js 计时器,定期更新倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个计时器命令,用户可以输入类似 [prefix]timer 10m 之类的内容,机器人将启动一个 10 分钟的计时器,并且每隔 20-30 秒它会自行更新,但我不确定如何我能做到这一点.提前致谢!

I'm currently making a timer command where a user could input something like [prefix]timer 10m and the bot will start a timer with 10 minutes, and every 20-30 seconds it updates itself, but I'm unsure how I could do it. Thanks in advance!

推荐答案

一种可能的方法是使用 setInterval() 函数.您可以在每次设置的时间间隔用完后使用它来调用回调函数.

One possible way to do this may be using the setInterval() function. You can use it to call a Callback-functions every time after a set interval has run out.

在您的情况下,此回调可能是一个函数,该函数更新一个变量,该变量用于以秒为单位存储计时器的剩余时间,例如像这样:

In your case, this Callback could be a function that updates a variable that is used to store the remaining time of the timer in seconds, e.g. like that:

var timer = 60;

setInterval(function () {
    timer--;
    console.log(timer);
}, 1000)

请注意,作为第二个参数给出的数字是以毫秒为单位的时间,因此 1000 毫秒将是一秒.如果你不希望函数每秒输出计时器的当前状态,你可以使用第二个setInterval(),它只触发所有30秒.

Note that the number given as a second argument is the time in miliseconds, so 1000ms would be one second. If you dont want the function to output the current state of the timer every second, you can use a second setInterval() that only triggers all 30 seconds.

您可以在 上找到有关 setInterval() 函数的更多示例w3schools.

You can find more examples for the setInterval() function on w3schools.

这篇关于Discord.js 计时器,定期更新倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆