'Discord.js v13 setTimeout() working differently than expected
I have this command which is supposed to ping a user 10 times, because of discord limitations it sends 5 pings and then has to wait a sec to send the next 5. I tried to make it send pings every 3 seconds to prevent that from happening but all it does is it waits 3 seconds before sending the first mention and that's it, the rest are send without any down time (except for discord limitations ofc). Anyone got a solution? Here's my code:
const { Permissions } = require('discord.js')
module.exports = {
name: 'pings',
description: "pings someone",
execute(message, args)
{
const target = message.mentions.members.first()
if (message.member.user.id === 'my discord id' || message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR))
{
if(target)
{
for(let i = 10; i > 0; i--)
{
setTimeout(function(){
message.channel.send(`<@${target.id}>`)
}, 3000);
}
}
else
{
message.reply('You have to mention someone in this server')
}
}
}
}
Solution 1:[1]
You can adjust the loop to do this. Currently this is what you have:
for(let i = 10; i > 0; i--)
{
setTimeout(function(){
message.channel.send(`<@${target.id}>`)
}, 3000);
}
But this just sends 10 messages with a 3 second delay (each message is sent after 3 seconds). Instead, do:
for(let i = 10; i > 0; i--)
{
setTimeout(function(){
message.channel.send(`<@${target.id}>`)
}, i*3000); // Adding i*3000
}
Now this will send 10 messages, one at 3, 6, 9... and 30 seconds.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JeremiahDuane |
