Reputation: 105
I have code for a massrole command, to give everyone on a server (excluding bots) a specific role:
message.guild.members.filter(m => !m.user.bot).forEach(member => {
member.addRole(roleNameFind);
console.log(`[LOG] Gave the role ${roleName} to ${member.user.tag}.`);
});
Both "roleNameFind" and "roleName" are defined. But how would I use setTimeout to run both member.addRole(roleNameFind);
and console.log(`[LOG] Gave the role ${roleName} to ${member.user.tag}.`);
every 5 seconds in the forEach thing?
Upvotes: 0
Views: 128
Reputation: 5174
You need to use setInterval()
not setTimeout()
for recurring functions.
I also suggest using client.setTimeout()
and client.setInterval()
instead of setTimeout()
and setInterval()
so that the timers can get cleared once the bot stops/restarts.
client.setInterval(() => {
const member = message.guild.members.filter(m => !m.user.bot).random()
if (!member.roles.some(role => role.name === roleNameFind)) {
member.addRole(roleNameFind);
console.log(`[LOG] Gave the role ${roleName} to ${member.user.tag}.`);
}
}, 5000)
Upvotes: 2
Reputation: 152
You can use setInterval
instead of setTimeout
. You can read the documentation here.
Upvotes: -1
Reputation: 392
Use setInterval
, it does exactly what you want.
var intervalId = setInterval(function() {
console.log("This function will be executed each 5 seconds!");
}, 5000);
More information of the Mozilla MDN.
To stop the interval on the last item, use clearInterval(intervalId);
Upvotes: 1