1

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);
    });
  }
}
4
  • 1
    Possible duplicate of Applying delay between iterations of javascript for loop Commented Aug 10, 2017 at 19:58
  • What is the purpose of this delay? Commented Aug 10, 2017 at 20:07
  • it is for a server, sending them all together sometimes causes corruption...., also i didn't notice older question! Commented Aug 10, 2017 at 20:08
  • Feels like a XY problem. What is the corruption that you're going to use this to try to avoid? Commented Aug 10, 2017 at 23:01

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.