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);
    });
  }
}
Roman
  • 4,922
  • 3
  • 22
  • 31
  • 1
    Possible duplicate of [Applying delay between iterations of javascript for loop](https://stackoverflow.com/questions/11764714/applying-delay-between-iterations-of-javascript-for-loop) – Joe B. Aug 10 '17 at 19:58
  • What is the purpose of this delay? – Kevin B Aug 10 '17 at 20:07
  • it is for a server, sending them all together sometimes causes corruption...., also i didn't notice older question! –  Aug 10 '17 at 20:08
  • Feels like a [XY problem](https://meta.stackexchange.com/a/66378/214286). What is the corruption that you're going to use this to try to avoid? – 1252748 Aug 10 '17 at 23:01

1 Answers1

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.

kkica
  • 4,034
  • 1
  • 20
  • 40