Reputation:
i wanna wait between each for loop for 3 seconds, i have tried lots of algorithms but none of them worked, can anyone help?
for (i = 0; i < members.length; i ++) {
console.log(members[i].username+" "+i);
if (!members[i].can(Discordie.Permissions.General.KICK_MEMBERS, guildthingy)) {
var dm = members[i].openDM();
console.log(members[i].username+" "+i+" "+dm);
dm.then(function (value) {
value.sendMessage(message);
console.log("MESSAGE SENT");
},
function (value) {
console.log(value);
});
}
}
Upvotes: 1
Views: 177
Reputation: 4104
You can do it like this.
for (i = 0; i < members.length; i ++){
(function(i){
setTimeout(function(){
console.log(members[i].username+" "+i);
if (!members[i].can(Discordie.Permissions.General.KICK_MEMBERS, guildthingy)){
var dm = members[i].openDM();
console.log(members[i].username+" "+i+" "+dm);
dm.then(function (value){
value.sendMessage(message);
console.log("MESSAGE SENT");
}, function (value){
console.log(value);
});
}
}, 3000 * i);//time in milliseconds
}(i));
}
The setTimeout
function, would apply the delay.
The immediately invocated anonymous function(IIAF), is to get the current value of i
in the loop.
Since javascript binds the variable i
late, all the callings of the function provided in the setTimeout
would get the same parameter i
if it was not for that IIAF. The latest one.
Upvotes: 3