Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 有没有办法使用setTimeout为我的代码添加冷却时间,这样人们就不会';你不发命令吗?_Javascript_Discord_Discord.js - Fatal编程技术网

Javascript 有没有办法使用setTimeout为我的代码添加冷却时间,这样人们就不会';你不发命令吗?

Javascript 有没有办法使用setTimeout为我的代码添加冷却时间,这样人们就不会';你不发命令吗?,javascript,discord,discord.js,Javascript,Discord,Discord.js,我只想有一种方法,每当用户试图运行它时,给它添加15分钟的冷却时间 如果命令处于冷却状态,是否有方法发送类似“您正在冷却(剩余时间)”的消息 我现在拥有的代码 var Money = (Money == null) ? 0: Money+= Math.floor(Math.random()*99) + 1; Money += Math.floor(Math.random() * 99) + 1; $halt $random{|||||||||Use /bal to check your bala

我只想有一种方法,每当用户试图运行它时,给它添加15分钟的冷却时间

如果命令处于冷却状态,是否有方法发送类似“您正在冷却(剩余时间)”的消息

我现在拥有的代码

var Money = (Money == null) ? 0: Money+= Math.floor(Math.random()*99) + 1;
Money += Math.floor(Math.random() * 99) + 1;
$halt
$random{|||||||||Use /bal to check your balance||}
**Balance: $$get(Money)**```

我认为您可以使用promise来完成顺序流程和冷却:

var延迟=功能{
返回新承诺(功能(解决、拒绝){
设置超时(解析,秒);
});
};
delay().then(函数()){
返回延迟(3000);//延迟3秒
}).然后(DoingSmth());

您可以将最后一个操作的时间戳保存在变量中,并检查从现在到最后一个时间戳所经过的时间

let lastActionTime = new Date();

let cooldown = () => {
let timeElapsed;
let now = new Date();
//get the actual time elapsed in ms
timeElapsed = now - lastActionTime;
//check if the time elapsed is less than 15 minute or not
if(timeElapsed < 900000){
//if yes, return message with remaining time in seconds
console.log(`You are on cooldown, remaining time ${(900000-timeElapsed)/1000} seconds`);
} else {
//Do the requested action and re-assign the lastActionTime
console.log(`Hurray`);
lastActionTime = new Date();
}
}
让lastActionTime=newdate();
让冷却时间=()=>{
让时间流逝;
让我们现在=新日期();
//获取实际经过的时间(毫秒)
timeappeased=now-lastActionTime;
//检查经过的时间是否小于15分钟
如果(经过的时间<900000){
//如果是,返回消息,剩余时间以秒为单位
log(`您正在冷却,剩余时间${(900000 timepassed)/1000}秒');
}否则{
//执行请求的操作并重新分配lastActionTime
console.log(`Hurray`);
lastActionTime=新日期();
}
}

在SPA(单页应用程序)中执行此操作的正确方法是在全局状态下保存过期时间(例如React中的Redux)-这样用户可以在页面间移动,“倒计时”仍然有效

如果您的应用程序不是SPA,您可以将过期日期保存在数据库中


关于建议在同一页面上实现该功能的其他答案,期望用户在同一页面上停留15分钟是不可行的。

我建议将此时间戳保存在地图或对象中。