How do I add a delay in a JavaScript loop?












281















I would like to add a delay/sleep inside a while loop:



I tried it like this:



alert('hi');

for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}


Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.



What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.










share|improve this question





























    281















    I would like to add a delay/sleep inside a while loop:



    I tried it like this:



    alert('hi');

    for(var start = 1; start < 10; start++) {
    setTimeout(function () {
    alert('hello');
    }, 3000);
    }


    Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.



    What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.










    share|improve this question



























      281












      281








      281


      122






      I would like to add a delay/sleep inside a while loop:



      I tried it like this:



      alert('hi');

      for(var start = 1; start < 10; start++) {
      setTimeout(function () {
      alert('hello');
      }, 3000);
      }


      Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.



      What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.










      share|improve this question
















      I would like to add a delay/sleep inside a while loop:



      I tried it like this:



      alert('hi');

      for(var start = 1; start < 10; start++) {
      setTimeout(function () {
      alert('hello');
      }, 3000);
      }


      Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.



      What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.







      javascript loops sleep






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 3 '18 at 16:19









      halfer

      14.7k759116




      14.7k759116










      asked Aug 27 '10 at 11:36









      olidevolidev

      7,01042112173




      7,01042112173
























          24 Answers
          24






          active

          oldest

          votes


















          645





          +50









          The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.



          You may want to use something like this instead:



          var i = 1;                     //  set your counter to 1

          function myLoop () { // create a loop function
          setTimeout(function () { // call a 3s setTimeout when the loop is called
          alert('hello'); // your code here
          i++; // increment the counter
          if (i < 10) { // if the counter < 10, call the loop function
          myLoop(); // .. again which will trigger another
          } // .. setTimeout()
          }, 3000)
          }

          myLoop(); // start the loop


          You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:



          (function myLoop (i) {          
          setTimeout(function () {
          alert('hello'); // your code here
          if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
          }, 3000)
          })(10); // pass the number of iterations as an argument





          share|improve this answer





















          • 16





            Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

            – Adam
            Jun 24 '14 at 21:15








          • 6





            @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

            – Joe
            Sep 2 '15 at 17:10






          • 3





            How would this work when iterating an object like a for in loop?

            – vsync
            Sep 14 '15 at 20:35








          • 1





            @vsync Look into Object.keys()

            – Braden Best
            Aug 12 '16 at 18:41








          • 1





            @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

            – cdhowie
            Mar 1 '18 at 18:08





















          58














          Try something like this:



          var i = 0, howManyTimes = 10;
          function f() {
          alert( "hi" );
          i++;
          if( i < howManyTimes ){
          setTimeout( f, 3000 );
          }
          }
          f();





          share|improve this answer



















          • 1





            This is perfect. Super simple and worked like a charm. Nice work!

            – Aarmora
            Apr 7 '16 at 16:08











          • Flawless! Simple.

            – Neo
            Jul 2 '18 at 2:28











          • eventually, found my answer thanks :)

            – Mesut GÜNEŞ
            Feb 8 at 11:40



















          45














          If using ES6, you could use let to achieve this:



          for (let i=1; i<10; i++) {
          setTimeout( function timer(){
          alert("hello world");
          }, i*3000 );
          }


          What let does is declare i for each iteration, not the loop. This way, what is passed to setTimeout is exactly what we want.






          share|improve this answer



















          • 1





            Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

            – Sophia Gold
            Jul 10 '16 at 1:46






          • 1





            I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

            – Flame_Phoenix
            Jul 21 '16 at 10:58











          • @Flame_Phoenix What memory allocation issues?

            – 4castle
            Jul 21 '17 at 0:29











          • The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

            – traktor53
            Nov 21 '18 at 0:58



















          21














          Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.



          for (var start = 1; start < 10; start++)
          setTimeout(function () { alert('hello'); }, 3000 * start);


          The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.






          share|improve this answer



















          • 2





            It's worth pointing out that you cannot reliably use start inside your function using this method.

            – DBS
            Jun 24 '15 at 13:17






          • 2





            Bad practice - unnecessary memory allocation.

            – Alexander Trakhimenok
            Oct 7 '15 at 15:37











          • Upvote for creativity, but it's damn bad practice. :)

            – Salivan
            Jun 27 '16 at 18:51






          • 2





            Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

            – Flame_Phoenix
            Jul 21 '16 at 11:00








          • 1





            @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

            – Joakim
            Aug 9 '18 at 18:18



















          18














          Since ES7 theres a better way to await a loop:



          function timer(ms) {
          return new Promise(res => setTimeout(res, ms));
          }

          async function load () {
          for (var i = 0; i < 3; i++) {
          console.log(i);
          await timer(3000);
          }
          }

          load();


          Reference on MDN



          Note that ES7 is rarely supported today, so you need to transpile with Babel to use it everywhere.



          Transpiled






          share|improve this answer


























          • It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

            – Sachin Shah
            Aug 7 '18 at 11:25











          • @sachin break; maybe?

            – Jonas Wilms
            Aug 7 '18 at 11:47



















          14














          I think you need something like this:



          var TimedQueue = function(defaultDelay){
          this.queue = ;
          this.index = 0;
          this.defaultDelay = defaultDelay || 3000;
          };

          TimedQueue.prototype = {
          add: function(fn, delay){
          this.queue.push({
          fn: fn,
          delay: delay
          });
          },
          run: function(index){
          (index || index === 0) && (this.index = index);
          this.next();
          },
          next: function(){
          var self = this
          , i = this.index++
          , at = this.queue[i]
          , next = this.queue[this.index]
          if(!at) return;
          at.fn();
          next && setTimeout(function(){
          self.next();
          }, next.delay||this.defaultDelay);
          },
          reset: function(){
          this.index = 0;
          }
          }


          Test code:



          var now = +new Date();

          var x = new TimedQueue(2000);

          x.add(function(){
          console.log('hey');
          console.log(+new Date() - now);
          });
          x.add(function(){
          console.log('ho');
          console.log(+new Date() - now);
          }, 3000);
          x.add(function(){
          console.log('bye');
          console.log(+new Date() - now);
          });

          x.run();


          Note: using alerts stalls javascript execution till you close the alert.
          It might be more code than you asked for, but this is a robust reusable solution.






          share|improve this answer































            13














            I would probably use setInteval. Like this,



            var period = 1000; // ms
            var endTime = 10000; // ms
            var counter = 0;
            var sleepyAlert = setInterval(function(){
            alert('Hello');
            if(counter === endTime){
            clearInterval(sleepyAlert);
            }
            counter += period;
            }, period);





            share|improve this answer



















            • 3





              SetTimeout is much better than settinterval. google it and you will know

              – Abdul Jabbar Dumrai
              Feb 23 '14 at 22:26






            • 13





              I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

              – Marcs
              Mar 20 '16 at 22:08











            • I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

              – Mateen Ulhaq
              Nov 21 '17 at 1:00





















            12














            This will work



            for (var i = 0; i < 10; i++) {
            (function(i) {
            setTimeout(function() { console.log(i); }, 100 * i);
            })(i);
            }


            Try this fiddle: https://jsfiddle.net/wgdx8zqq/






            share|improve this answer



















            • 1





              This does trigger all timeout calls near the same time though

              – Eddie
              Apr 10 '18 at 19:19











            • the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

              – ArifMustafa
              Oct 20 '18 at 6:55



















            7














            In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.




            Generators, a new feature of ECMAScript 6, are functions that can be
            paused and resumed. Calling genFunc does not execute it. Instead, it
            returns a so-called generator object that lets us control genFunc’s
            execution. genFunc() is initially suspended at the beginning of its
            body. The method genObj.next() continues the execution of genFunc,
            until the next yield.
            (Exploring ES6)





            Code example:




            let arr = [1, 2, 3, 'b'];
            let genObj = genFunc();

            let val = genObj.next();
            console.log(val.value);

            let interval = setInterval(() => {
            val = genObj.next();

            if (val.done) {
            clearInterval(interval);
            } else {
            console.log(val.value);
            }
            }, 1000);

            function* genFunc() {
            for(let item of arr) {
            yield item;
            }
            }





            So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).






            share|improve this answer































              4














              I do this with Bluebird’s Promise.delay and recursion.






              function myLoop(i) {
              return Promise.delay(1000)
              .then(function() {
              if (i > 0) {
              alert('hello');
              return myLoop(i -= 1);
              }
              });
              }

              myLoop(3);

              <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>








              share|improve this answer

































                3














                Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:



                function timeout(range, time, callback){
                var i = range[0];
                callback(i);
                Loop();
                function Loop(){
                setTimeout(function(){
                i++;
                if (i<range[1]){
                callback(i);
                Loop();
                }
                }, time*1000)
                }
                }


                For example:



                //This function prints the loop number every second
                timeout([0, 5], 1, function(i){
                console.log(i);
                });


                Would be equivalent to:



                //This function prints the loop number instantly
                for (var i = 0; i<5; i++){
                console.log(i);
                }





                share|improve this answer

































                  2














                  You can use RxJS interval operator. Interval emits integer every x number of seconds, and take is specify number of times it has to emit numberss






                  Rx.Observable
                  .interval(1000)
                  .take(10)
                  .subscribe((x) => console.log(x))

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>








                  share|improve this answer































                    1

















                        var startIndex = 0;
                    var data = [1, 2, 3];
                    var timeout = 1000;

                    function functionToRun(i, length) {
                    alert(data[i]);
                    }

                    (function forWithDelay(i, length, fn, delay) {
                    setTimeout(function() {
                    fn(i, length);
                    i++;
                    if (i < length) {
                    forWithDelay(i, length, fn, delay);
                    }
                    }, delay);
                    })(startIndex, data.length, functionToRun, timeout);





                    A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:



                    First let's define some essential variables:



                    var startIndex = 0;
                    var data = [1, 2, 3];
                    var timeout = 3000;


                    Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:



                    function functionToRun(i, length) {
                    alert(data[i]);
                    }


                    Self-executing version



                    (function forWithDelay(i, length, fn, delay) {
                    setTimeout(function () {
                    fn(i, length);
                    i++;
                    if (i < length) {
                    forWithDelay(i, length, fn, delay);
                    }
                    }, delay);
                    })(startIndex, data.length, functionToRun, timeout);


                    Functional version



                    function forWithDelay(i, length, fn, delay) {
                    setTimeout(function () {
                    fn(i, length);
                    i++;
                    if (i < length) {
                    forWithDelay(i, length, fn, delay);
                    }
                    }, delay);
                    }

                    forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it





                    share|improve this answer
























                    • nice one and how do I pass data to the function without a global variable

                      – Sundara Prabu
                      May 29 '17 at 17:54



















                    0














                    /* 
                    Use Recursive and setTimeout
                    call below function will run loop loopFunctionNeedCheck until
                    conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
                    reRunAfterMs miliseconds and continue loop
                    tested code, thanks
                    */

                    function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                    loopFunctionNeedCheck) {
                    loopFunctionNeedCheck();
                    var result = conditionCheckAfterRunFn();
                    //check after run
                    if (!result) {
                    setTimeout(function () {
                    functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                    }, reRunAfterMs);
                    }
                    else console.log("completed, thanks");
                    //if you need call a function after completed add code call callback in here
                    }

                    //passing-parameters-to-a-callback-function
                    // From Prototype.js
                    if (!Function.prototype.bind) { // check if native implementation available
                    Function.prototype.bind = function () {
                    var fn = this, args = Array.prototype.slice.call(arguments),
                    object = args.shift();
                    return function () {
                    return fn.apply(object,
                    args.concat(Array.prototype.slice.call(arguments)));
                    };
                    };
                    }

                    //test code:
                    var result = 0;
                    console.log("---> init result is " + result);
                    var functionNeedRun = function (step) {
                    result+=step;
                    console.log("current result is " + result);
                    }
                    var checkResultFunction = function () {
                    return result==100;
                    }

                    //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
                    functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));

                    //result log from console:
                    /*
                    ---> init result is 0
                    current result is 5
                    undefined
                    current result is 10
                    current result is 15
                    current result is 20
                    current result is 25
                    current result is 30
                    current result is 35
                    current result is 40
                    current result is 45
                    current result is 50
                    current result is 55
                    current result is 60
                    current result is 65
                    current result is 70
                    current result is 75
                    current result is 80
                    current result is 85
                    current result is 90
                    current result is 95
                    current result is 100
                    completed, thanks
                    */





                    share|improve this answer



















                    • 7





                      Your function names are horrendous, that's the main reason why this code is so hard to read.

                      – Mark Walters
                      Nov 26 '13 at 15:11



















                    0














                    Here is how I created an infinite loop with a delay that breaks on a certain condition:



                      // Now continuously check the app status until it's completed, 
                    // failed or times out. The isFinished() will throw exception if
                    // there is a failure.
                    while (true) {
                    let status = await this.api.getStatus(appId);
                    if (isFinished(status)) {
                    break;
                    } else {
                    // Delay before running the next loop iteration:
                    await new Promise(resolve => setTimeout(resolve, 3000));
                    }
                    }


                    The key here is to create a new Promise that resolves by timeout, and to await for its resolution.



                    Obviously you need async/await support for that. Works in Node 8.






                    share|improve this answer

































                      0














                      for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).



                              function iAsk(lvl){
                      var i=0;
                      var intr =setInterval(function(){ // start the loop
                      i++; // increment it
                      if(i>lvl){ // check if the end round reached.
                      clearInterval(intr);
                      return;
                      }
                      setTimeout(function(){
                      $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                      },50);
                      setTimeout(function(){
                      // do another bla bla bla after 100 millisecond.
                      seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                      $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                      $("#d"+seq[i-1]).prop("src",pGif);
                      var d =document.getElementById('aud');
                      d.play();
                      },100);
                      setTimeout(function(){
                      // keep adding bla bla bla till you done :)
                      $("#d"+seq[i-1]).prop("src",pPng);
                      },900);
                      },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                      }


                      PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.



                      PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..






                      share|improve this answer































                        0

















                        <!DOCTYPE html>
                        <html>
                        <body>

                        <button onclick="myFunction()">Try it</button>

                        <p id="demo"></p>

                        <script>
                        function myFunction() {
                        for(var i=0; i<5; i++) {
                        var sno = i+1;
                        (function myLoop (i) {
                        setTimeout(function () {
                        alert(i); // Do your function here
                        }, 1000*i);
                        })(sno);
                        }
                        }
                        </script>

                        </body>
                        </html>








                        share|improve this answer



















                        • 1





                          Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                          – Hexfire
                          Jan 23 '18 at 7:47






                        • 1





                          Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                          – WhatsThePoint
                          Jan 23 '18 at 7:58



















                        0














                        Simple implementation of showing a piece of text every two seconds as long the loop is running.



                        for (var i = 0; i < foo.length; i++) {
                        setInterval(function(){
                        console.log("I will appear every 2 seconds");
                        }, 2000);
                        break;
                        };





                        share|improve this answer































                          0














                          To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:



                          var looper = async function () {
                          for (var start = 1; start < 10; start++) {
                          await new Promise(function (resolve, reject) {
                          setTimeout(function () {
                          console.log("iteration: " + start.toString());
                          resolve(true);
                          }, 1000);
                          });
                          }
                          return true;
                          }


                          And then you call run it like so:



                          looper().then(function(){
                          console.log("DONE!")
                          });


                          Please take some time to get a good understanding of asynchronous programming.






                          share|improve this answer































                            -1














                            Here is a function that I use for looping over an array:



                            function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

                            if (i < theArray.length && typeof delayAmount == 'number'){

                            console.log("i "+i);

                            theFunction(theArray[i], i);

                            setTimeout(function(){

                            loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                            }else{

                            onComplete(i);
                            }
                            }


                            You use it like this:



                            loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                            //Do something with item
                            }, function(i){
                            //Do something once loop has completed
                            }





                            share|improve this answer































                              -1














                              This script works for most things



                              function timer(start) {
                              setTimeout(function () { //The timer
                              alert('hello');
                              }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                              }

                              for(var start = 1; start < 10; start++) {
                              timer(start);
                              }





                              share|improve this answer































                                -1

















                                var timer, i = 10;
                                function myLoop () { // create a loop function
                                timer = setTimeout(function () {
                                document.getElementById("demo").innerHTML = i;

                                i--;
                                if (i >= 0) {
                                myLoop();
                                } else {
                                clearTimeout(timer); // clear timeout
                                document.getElementById("demo").innerHTML = "DOARRRR ..";
                                }

                                }, 1000);
                                }

                                myLoop();

                                <p id="demo">count</p>








                                share|improve this answer































                                  -1














                                  Try this...



                                  var icount=0;
                                  for (let i in items) {
                                  icount=icount+1000;
                                  new beginCount(items[i],icount);
                                  }

                                  function beginCount(item,icount){
                                  setTimeout(function () {

                                  new actualFunction(item,icount);

                                  }, icount);
                                  }

                                  function actualFunction(item,icount){
                                  //...runs ever 1 second
                                  console.log(icount);
                                  }





                                  share|improve this answer































                                    -2














                                    Try this



                                    //the code will execute in 1 3 5 7 9 seconds later
                                    function exec(){
                                    for(var i=0;i<5;i++){
                                    setTimeout(function(){
                                    console.log(new Date()); //It's you code
                                    },(i+i+1)*1000);
                                    }
                                    }





                                    share|improve this answer

























                                      Your Answer






                                      StackExchange.ifUsing("editor", function () {
                                      StackExchange.using("externalEditor", function () {
                                      StackExchange.using("snippets", function () {
                                      StackExchange.snippets.init();
                                      });
                                      });
                                      }, "code-snippets");

                                      StackExchange.ready(function() {
                                      var channelOptions = {
                                      tags: "".split(" "),
                                      id: "1"
                                      };
                                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                      StackExchange.using("externalEditor", function() {
                                      // Have to fire editor after snippets, if snippets enabled
                                      if (StackExchange.settings.snippets.snippetsEnabled) {
                                      StackExchange.using("snippets", function() {
                                      createEditor();
                                      });
                                      }
                                      else {
                                      createEditor();
                                      }
                                      });

                                      function createEditor() {
                                      StackExchange.prepareEditor({
                                      heartbeatType: 'answer',
                                      autoActivateHeartbeat: false,
                                      convertImagesToLinks: true,
                                      noModals: true,
                                      showLowRepImageUploadWarning: true,
                                      reputationToPostImages: 10,
                                      bindNavPrevention: true,
                                      postfix: "",
                                      imageUploader: {
                                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                      allowUrls: true
                                      },
                                      onDemand: true,
                                      discardSelector: ".discard-answer"
                                      ,immediatelyShowMarkdownHelp:true
                                      });


                                      }
                                      });














                                      draft saved

                                      draft discarded


















                                      StackExchange.ready(
                                      function () {
                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3583724%2fhow-do-i-add-a-delay-in-a-javascript-loop%23new-answer', 'question_page');
                                      }
                                      );

                                      Post as a guest















                                      Required, but never shown

























                                      24 Answers
                                      24






                                      active

                                      oldest

                                      votes








                                      24 Answers
                                      24






                                      active

                                      oldest

                                      votes









                                      active

                                      oldest

                                      votes






                                      active

                                      oldest

                                      votes









                                      645





                                      +50









                                      The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.



                                      You may want to use something like this instead:



                                      var i = 1;                     //  set your counter to 1

                                      function myLoop () { // create a loop function
                                      setTimeout(function () { // call a 3s setTimeout when the loop is called
                                      alert('hello'); // your code here
                                      i++; // increment the counter
                                      if (i < 10) { // if the counter < 10, call the loop function
                                      myLoop(); // .. again which will trigger another
                                      } // .. setTimeout()
                                      }, 3000)
                                      }

                                      myLoop(); // start the loop


                                      You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:



                                      (function myLoop (i) {          
                                      setTimeout(function () {
                                      alert('hello'); // your code here
                                      if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
                                      }, 3000)
                                      })(10); // pass the number of iterations as an argument





                                      share|improve this answer





















                                      • 16





                                        Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                        – Adam
                                        Jun 24 '14 at 21:15








                                      • 6





                                        @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                        – Joe
                                        Sep 2 '15 at 17:10






                                      • 3





                                        How would this work when iterating an object like a for in loop?

                                        – vsync
                                        Sep 14 '15 at 20:35








                                      • 1





                                        @vsync Look into Object.keys()

                                        – Braden Best
                                        Aug 12 '16 at 18:41








                                      • 1





                                        @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                        – cdhowie
                                        Mar 1 '18 at 18:08


















                                      645





                                      +50









                                      The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.



                                      You may want to use something like this instead:



                                      var i = 1;                     //  set your counter to 1

                                      function myLoop () { // create a loop function
                                      setTimeout(function () { // call a 3s setTimeout when the loop is called
                                      alert('hello'); // your code here
                                      i++; // increment the counter
                                      if (i < 10) { // if the counter < 10, call the loop function
                                      myLoop(); // .. again which will trigger another
                                      } // .. setTimeout()
                                      }, 3000)
                                      }

                                      myLoop(); // start the loop


                                      You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:



                                      (function myLoop (i) {          
                                      setTimeout(function () {
                                      alert('hello'); // your code here
                                      if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
                                      }, 3000)
                                      })(10); // pass the number of iterations as an argument





                                      share|improve this answer





















                                      • 16





                                        Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                        – Adam
                                        Jun 24 '14 at 21:15








                                      • 6





                                        @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                        – Joe
                                        Sep 2 '15 at 17:10






                                      • 3





                                        How would this work when iterating an object like a for in loop?

                                        – vsync
                                        Sep 14 '15 at 20:35








                                      • 1





                                        @vsync Look into Object.keys()

                                        – Braden Best
                                        Aug 12 '16 at 18:41








                                      • 1





                                        @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                        – cdhowie
                                        Mar 1 '18 at 18:08
















                                      645





                                      +50







                                      645





                                      +50



                                      645




                                      +50





                                      The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.



                                      You may want to use something like this instead:



                                      var i = 1;                     //  set your counter to 1

                                      function myLoop () { // create a loop function
                                      setTimeout(function () { // call a 3s setTimeout when the loop is called
                                      alert('hello'); // your code here
                                      i++; // increment the counter
                                      if (i < 10) { // if the counter < 10, call the loop function
                                      myLoop(); // .. again which will trigger another
                                      } // .. setTimeout()
                                      }, 3000)
                                      }

                                      myLoop(); // start the loop


                                      You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:



                                      (function myLoop (i) {          
                                      setTimeout(function () {
                                      alert('hello'); // your code here
                                      if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
                                      }, 3000)
                                      })(10); // pass the number of iterations as an argument





                                      share|improve this answer















                                      The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.



                                      You may want to use something like this instead:



                                      var i = 1;                     //  set your counter to 1

                                      function myLoop () { // create a loop function
                                      setTimeout(function () { // call a 3s setTimeout when the loop is called
                                      alert('hello'); // your code here
                                      i++; // increment the counter
                                      if (i < 10) { // if the counter < 10, call the loop function
                                      myLoop(); // .. again which will trigger another
                                      } // .. setTimeout()
                                      }, 3000)
                                      }

                                      myLoop(); // start the loop


                                      You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:



                                      (function myLoop (i) {          
                                      setTimeout(function () {
                                      alert('hello'); // your code here
                                      if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
                                      }, 3000)
                                      })(10); // pass the number of iterations as an argument






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Aug 27 '10 at 12:07

























                                      answered Aug 27 '10 at 11:38









                                      Daniel VassalloDaniel Vassallo

                                      273k60450407




                                      273k60450407








                                      • 16





                                        Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                        – Adam
                                        Jun 24 '14 at 21:15








                                      • 6





                                        @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                        – Joe
                                        Sep 2 '15 at 17:10






                                      • 3





                                        How would this work when iterating an object like a for in loop?

                                        – vsync
                                        Sep 14 '15 at 20:35








                                      • 1





                                        @vsync Look into Object.keys()

                                        – Braden Best
                                        Aug 12 '16 at 18:41








                                      • 1





                                        @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                        – cdhowie
                                        Mar 1 '18 at 18:08
















                                      • 16





                                        Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                        – Adam
                                        Jun 24 '14 at 21:15








                                      • 6





                                        @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                        – Joe
                                        Sep 2 '15 at 17:10






                                      • 3





                                        How would this work when iterating an object like a for in loop?

                                        – vsync
                                        Sep 14 '15 at 20:35








                                      • 1





                                        @vsync Look into Object.keys()

                                        – Braden Best
                                        Aug 12 '16 at 18:41








                                      • 1





                                        @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                        – cdhowie
                                        Mar 1 '18 at 18:08










                                      16




                                      16





                                      Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                      – Adam
                                      Jun 24 '14 at 21:15







                                      Wouldn't using recursion to implement this be subject to a stack overflow eventually? If you wanted to do a million iterations, what would be a better way to implement this? Maybe setInterval and then clear it, like Abel's solution below?

                                      – Adam
                                      Jun 24 '14 at 21:15






                                      6




                                      6





                                      @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                      – Joe
                                      Sep 2 '15 at 17:10





                                      @Adam: my understanding is that, since setTimeout is non-blocking, this isn't recusion - the stackwindow closes after each setTimeout and there is only ever one setTimeout waiting to execute...Right?

                                      – Joe
                                      Sep 2 '15 at 17:10




                                      3




                                      3





                                      How would this work when iterating an object like a for in loop?

                                      – vsync
                                      Sep 14 '15 at 20:35







                                      How would this work when iterating an object like a for in loop?

                                      – vsync
                                      Sep 14 '15 at 20:35






                                      1




                                      1





                                      @vsync Look into Object.keys()

                                      – Braden Best
                                      Aug 12 '16 at 18:41







                                      @vsync Look into Object.keys()

                                      – Braden Best
                                      Aug 12 '16 at 18:41






                                      1




                                      1





                                      @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                      – cdhowie
                                      Mar 1 '18 at 18:08







                                      @joey You are confusing setTimeout with setInterval. Timeouts are implicitly destroyed when the callback is called.

                                      – cdhowie
                                      Mar 1 '18 at 18:08















                                      58














                                      Try something like this:



                                      var i = 0, howManyTimes = 10;
                                      function f() {
                                      alert( "hi" );
                                      i++;
                                      if( i < howManyTimes ){
                                      setTimeout( f, 3000 );
                                      }
                                      }
                                      f();





                                      share|improve this answer



















                                      • 1





                                        This is perfect. Super simple and worked like a charm. Nice work!

                                        – Aarmora
                                        Apr 7 '16 at 16:08











                                      • Flawless! Simple.

                                        – Neo
                                        Jul 2 '18 at 2:28











                                      • eventually, found my answer thanks :)

                                        – Mesut GÜNEŞ
                                        Feb 8 at 11:40
















                                      58














                                      Try something like this:



                                      var i = 0, howManyTimes = 10;
                                      function f() {
                                      alert( "hi" );
                                      i++;
                                      if( i < howManyTimes ){
                                      setTimeout( f, 3000 );
                                      }
                                      }
                                      f();





                                      share|improve this answer



















                                      • 1





                                        This is perfect. Super simple and worked like a charm. Nice work!

                                        – Aarmora
                                        Apr 7 '16 at 16:08











                                      • Flawless! Simple.

                                        – Neo
                                        Jul 2 '18 at 2:28











                                      • eventually, found my answer thanks :)

                                        – Mesut GÜNEŞ
                                        Feb 8 at 11:40














                                      58












                                      58








                                      58







                                      Try something like this:



                                      var i = 0, howManyTimes = 10;
                                      function f() {
                                      alert( "hi" );
                                      i++;
                                      if( i < howManyTimes ){
                                      setTimeout( f, 3000 );
                                      }
                                      }
                                      f();





                                      share|improve this answer













                                      Try something like this:



                                      var i = 0, howManyTimes = 10;
                                      function f() {
                                      alert( "hi" );
                                      i++;
                                      if( i < howManyTimes ){
                                      setTimeout( f, 3000 );
                                      }
                                      }
                                      f();






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 27 '10 at 11:40









                                      cjicji

                                      5,43021615




                                      5,43021615








                                      • 1





                                        This is perfect. Super simple and worked like a charm. Nice work!

                                        – Aarmora
                                        Apr 7 '16 at 16:08











                                      • Flawless! Simple.

                                        – Neo
                                        Jul 2 '18 at 2:28











                                      • eventually, found my answer thanks :)

                                        – Mesut GÜNEŞ
                                        Feb 8 at 11:40














                                      • 1





                                        This is perfect. Super simple and worked like a charm. Nice work!

                                        – Aarmora
                                        Apr 7 '16 at 16:08











                                      • Flawless! Simple.

                                        – Neo
                                        Jul 2 '18 at 2:28











                                      • eventually, found my answer thanks :)

                                        – Mesut GÜNEŞ
                                        Feb 8 at 11:40








                                      1




                                      1





                                      This is perfect. Super simple and worked like a charm. Nice work!

                                      – Aarmora
                                      Apr 7 '16 at 16:08





                                      This is perfect. Super simple and worked like a charm. Nice work!

                                      – Aarmora
                                      Apr 7 '16 at 16:08













                                      Flawless! Simple.

                                      – Neo
                                      Jul 2 '18 at 2:28





                                      Flawless! Simple.

                                      – Neo
                                      Jul 2 '18 at 2:28













                                      eventually, found my answer thanks :)

                                      – Mesut GÜNEŞ
                                      Feb 8 at 11:40





                                      eventually, found my answer thanks :)

                                      – Mesut GÜNEŞ
                                      Feb 8 at 11:40











                                      45














                                      If using ES6, you could use let to achieve this:



                                      for (let i=1; i<10; i++) {
                                      setTimeout( function timer(){
                                      alert("hello world");
                                      }, i*3000 );
                                      }


                                      What let does is declare i for each iteration, not the loop. This way, what is passed to setTimeout is exactly what we want.






                                      share|improve this answer



















                                      • 1





                                        Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                        – Sophia Gold
                                        Jul 10 '16 at 1:46






                                      • 1





                                        I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 10:58











                                      • @Flame_Phoenix What memory allocation issues?

                                        – 4castle
                                        Jul 21 '17 at 0:29











                                      • The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                        – traktor53
                                        Nov 21 '18 at 0:58
















                                      45














                                      If using ES6, you could use let to achieve this:



                                      for (let i=1; i<10; i++) {
                                      setTimeout( function timer(){
                                      alert("hello world");
                                      }, i*3000 );
                                      }


                                      What let does is declare i for each iteration, not the loop. This way, what is passed to setTimeout is exactly what we want.






                                      share|improve this answer



















                                      • 1





                                        Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                        – Sophia Gold
                                        Jul 10 '16 at 1:46






                                      • 1





                                        I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 10:58











                                      • @Flame_Phoenix What memory allocation issues?

                                        – 4castle
                                        Jul 21 '17 at 0:29











                                      • The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                        – traktor53
                                        Nov 21 '18 at 0:58














                                      45












                                      45








                                      45







                                      If using ES6, you could use let to achieve this:



                                      for (let i=1; i<10; i++) {
                                      setTimeout( function timer(){
                                      alert("hello world");
                                      }, i*3000 );
                                      }


                                      What let does is declare i for each iteration, not the loop. This way, what is passed to setTimeout is exactly what we want.






                                      share|improve this answer













                                      If using ES6, you could use let to achieve this:



                                      for (let i=1; i<10; i++) {
                                      setTimeout( function timer(){
                                      alert("hello world");
                                      }, i*3000 );
                                      }


                                      What let does is declare i for each iteration, not the loop. This way, what is passed to setTimeout is exactly what we want.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 15 '16 at 17:47









                                      Saket MehtaSaket Mehta

                                      1,19511625




                                      1,19511625








                                      • 1





                                        Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                        – Sophia Gold
                                        Jul 10 '16 at 1:46






                                      • 1





                                        I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 10:58











                                      • @Flame_Phoenix What memory allocation issues?

                                        – 4castle
                                        Jul 21 '17 at 0:29











                                      • The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                        – traktor53
                                        Nov 21 '18 at 0:58














                                      • 1





                                        Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                        – Sophia Gold
                                        Jul 10 '16 at 1:46






                                      • 1





                                        I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 10:58











                                      • @Flame_Phoenix What memory allocation issues?

                                        – 4castle
                                        Jul 21 '17 at 0:29











                                      • The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                        – traktor53
                                        Nov 21 '18 at 0:58








                                      1




                                      1





                                      Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                      – Sophia Gold
                                      Jul 10 '16 at 1:46





                                      Thank! Wouldn't have thought of this method on my own. Actual block scoping. Imagine that...

                                      – Sophia Gold
                                      Jul 10 '16 at 1:46




                                      1




                                      1





                                      I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                      – Flame_Phoenix
                                      Jul 21 '16 at 10:58





                                      I believe this has the same memory allocation issues as the answer described in stackoverflow.com/a/3583795/1337392

                                      – Flame_Phoenix
                                      Jul 21 '16 at 10:58













                                      @Flame_Phoenix What memory allocation issues?

                                      – 4castle
                                      Jul 21 '17 at 0:29





                                      @Flame_Phoenix What memory allocation issues?

                                      – 4castle
                                      Jul 21 '17 at 0:29













                                      The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                      – traktor53
                                      Nov 21 '18 at 0:58





                                      The setTimeout call synchronously calculates the value of the i*3000 argument, inside the loop, and passes it to setTimeout by value. Usage of let is optional and unrelated to the questionl and answer.

                                      – traktor53
                                      Nov 21 '18 at 0:58











                                      21














                                      Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.



                                      for (var start = 1; start < 10; start++)
                                      setTimeout(function () { alert('hello'); }, 3000 * start);


                                      The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.






                                      share|improve this answer



















                                      • 2





                                        It's worth pointing out that you cannot reliably use start inside your function using this method.

                                        – DBS
                                        Jun 24 '15 at 13:17






                                      • 2





                                        Bad practice - unnecessary memory allocation.

                                        – Alexander Trakhimenok
                                        Oct 7 '15 at 15:37











                                      • Upvote for creativity, but it's damn bad practice. :)

                                        – Salivan
                                        Jun 27 '16 at 18:51






                                      • 2





                                        Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 11:00








                                      • 1





                                        @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                        – Joakim
                                        Aug 9 '18 at 18:18
















                                      21














                                      Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.



                                      for (var start = 1; start < 10; start++)
                                      setTimeout(function () { alert('hello'); }, 3000 * start);


                                      The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.






                                      share|improve this answer



















                                      • 2





                                        It's worth pointing out that you cannot reliably use start inside your function using this method.

                                        – DBS
                                        Jun 24 '15 at 13:17






                                      • 2





                                        Bad practice - unnecessary memory allocation.

                                        – Alexander Trakhimenok
                                        Oct 7 '15 at 15:37











                                      • Upvote for creativity, but it's damn bad practice. :)

                                        – Salivan
                                        Jun 27 '16 at 18:51






                                      • 2





                                        Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 11:00








                                      • 1





                                        @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                        – Joakim
                                        Aug 9 '18 at 18:18














                                      21












                                      21








                                      21







                                      Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.



                                      for (var start = 1; start < 10; start++)
                                      setTimeout(function () { alert('hello'); }, 3000 * start);


                                      The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.






                                      share|improve this answer













                                      Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.



                                      for (var start = 1; start < 10; start++)
                                      setTimeout(function () { alert('hello'); }, 3000 * start);


                                      The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 27 '10 at 11:48









                                      Felix KlingFelix Kling

                                      561k130870932




                                      561k130870932








                                      • 2





                                        It's worth pointing out that you cannot reliably use start inside your function using this method.

                                        – DBS
                                        Jun 24 '15 at 13:17






                                      • 2





                                        Bad practice - unnecessary memory allocation.

                                        – Alexander Trakhimenok
                                        Oct 7 '15 at 15:37











                                      • Upvote for creativity, but it's damn bad practice. :)

                                        – Salivan
                                        Jun 27 '16 at 18:51






                                      • 2





                                        Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 11:00








                                      • 1





                                        @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                        – Joakim
                                        Aug 9 '18 at 18:18














                                      • 2





                                        It's worth pointing out that you cannot reliably use start inside your function using this method.

                                        – DBS
                                        Jun 24 '15 at 13:17






                                      • 2





                                        Bad practice - unnecessary memory allocation.

                                        – Alexander Trakhimenok
                                        Oct 7 '15 at 15:37











                                      • Upvote for creativity, but it's damn bad practice. :)

                                        – Salivan
                                        Jun 27 '16 at 18:51






                                      • 2





                                        Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                        – Flame_Phoenix
                                        Jul 21 '16 at 11:00








                                      • 1





                                        @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                        – Joakim
                                        Aug 9 '18 at 18:18








                                      2




                                      2





                                      It's worth pointing out that you cannot reliably use start inside your function using this method.

                                      – DBS
                                      Jun 24 '15 at 13:17





                                      It's worth pointing out that you cannot reliably use start inside your function using this method.

                                      – DBS
                                      Jun 24 '15 at 13:17




                                      2




                                      2





                                      Bad practice - unnecessary memory allocation.

                                      – Alexander Trakhimenok
                                      Oct 7 '15 at 15:37





                                      Bad practice - unnecessary memory allocation.

                                      – Alexander Trakhimenok
                                      Oct 7 '15 at 15:37













                                      Upvote for creativity, but it's damn bad practice. :)

                                      – Salivan
                                      Jun 27 '16 at 18:51





                                      Upvote for creativity, but it's damn bad practice. :)

                                      – Salivan
                                      Jun 27 '16 at 18:51




                                      2




                                      2





                                      Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                      – Flame_Phoenix
                                      Jul 21 '16 at 11:00







                                      Why is it a bad practice, and why does it have memory allocation issues ? Does this answer suffer the same problems? stackoverflow.com/a/36018502/1337392

                                      – Flame_Phoenix
                                      Jul 21 '16 at 11:00






                                      1




                                      1





                                      @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                      – Joakim
                                      Aug 9 '18 at 18:18





                                      @Flame_Phoenix it's bad practice because the program will keep one timer for each loop, with all timers running at the same time. So if there are 1000 iterations, there will be 1000 timers running at the same time in the beginning.

                                      – Joakim
                                      Aug 9 '18 at 18:18











                                      18














                                      Since ES7 theres a better way to await a loop:



                                      function timer(ms) {
                                      return new Promise(res => setTimeout(res, ms));
                                      }

                                      async function load () {
                                      for (var i = 0; i < 3; i++) {
                                      console.log(i);
                                      await timer(3000);
                                      }
                                      }

                                      load();


                                      Reference on MDN



                                      Note that ES7 is rarely supported today, so you need to transpile with Babel to use it everywhere.



                                      Transpiled






                                      share|improve this answer


























                                      • It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                        – Sachin Shah
                                        Aug 7 '18 at 11:25











                                      • @sachin break; maybe?

                                        – Jonas Wilms
                                        Aug 7 '18 at 11:47
















                                      18














                                      Since ES7 theres a better way to await a loop:



                                      function timer(ms) {
                                      return new Promise(res => setTimeout(res, ms));
                                      }

                                      async function load () {
                                      for (var i = 0; i < 3; i++) {
                                      console.log(i);
                                      await timer(3000);
                                      }
                                      }

                                      load();


                                      Reference on MDN



                                      Note that ES7 is rarely supported today, so you need to transpile with Babel to use it everywhere.



                                      Transpiled






                                      share|improve this answer


























                                      • It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                        – Sachin Shah
                                        Aug 7 '18 at 11:25











                                      • @sachin break; maybe?

                                        – Jonas Wilms
                                        Aug 7 '18 at 11:47














                                      18












                                      18








                                      18







                                      Since ES7 theres a better way to await a loop:



                                      function timer(ms) {
                                      return new Promise(res => setTimeout(res, ms));
                                      }

                                      async function load () {
                                      for (var i = 0; i < 3; i++) {
                                      console.log(i);
                                      await timer(3000);
                                      }
                                      }

                                      load();


                                      Reference on MDN



                                      Note that ES7 is rarely supported today, so you need to transpile with Babel to use it everywhere.



                                      Transpiled






                                      share|improve this answer















                                      Since ES7 theres a better way to await a loop:



                                      function timer(ms) {
                                      return new Promise(res => setTimeout(res, ms));
                                      }

                                      async function load () {
                                      for (var i = 0; i < 3; i++) {
                                      console.log(i);
                                      await timer(3000);
                                      }
                                      }

                                      load();


                                      Reference on MDN



                                      Note that ES7 is rarely supported today, so you need to transpile with Babel to use it everywhere.



                                      Transpiled







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Dec 19 '18 at 15:31

























                                      answered Jun 10 '17 at 18:19









                                      Jonas WilmsJonas Wilms

                                      63.3k53457




                                      63.3k53457













                                      • It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                        – Sachin Shah
                                        Aug 7 '18 at 11:25











                                      • @sachin break; maybe?

                                        – Jonas Wilms
                                        Aug 7 '18 at 11:47



















                                      • It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                        – Sachin Shah
                                        Aug 7 '18 at 11:25











                                      • @sachin break; maybe?

                                        – Jonas Wilms
                                        Aug 7 '18 at 11:47

















                                      It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                      – Sachin Shah
                                      Aug 7 '18 at 11:25





                                      It works fine for me. I just want to ask that if I want to break loop , how can I do it when using await ?

                                      – Sachin Shah
                                      Aug 7 '18 at 11:25













                                      @sachin break; maybe?

                                      – Jonas Wilms
                                      Aug 7 '18 at 11:47





                                      @sachin break; maybe?

                                      – Jonas Wilms
                                      Aug 7 '18 at 11:47











                                      14














                                      I think you need something like this:



                                      var TimedQueue = function(defaultDelay){
                                      this.queue = ;
                                      this.index = 0;
                                      this.defaultDelay = defaultDelay || 3000;
                                      };

                                      TimedQueue.prototype = {
                                      add: function(fn, delay){
                                      this.queue.push({
                                      fn: fn,
                                      delay: delay
                                      });
                                      },
                                      run: function(index){
                                      (index || index === 0) && (this.index = index);
                                      this.next();
                                      },
                                      next: function(){
                                      var self = this
                                      , i = this.index++
                                      , at = this.queue[i]
                                      , next = this.queue[this.index]
                                      if(!at) return;
                                      at.fn();
                                      next && setTimeout(function(){
                                      self.next();
                                      }, next.delay||this.defaultDelay);
                                      },
                                      reset: function(){
                                      this.index = 0;
                                      }
                                      }


                                      Test code:



                                      var now = +new Date();

                                      var x = new TimedQueue(2000);

                                      x.add(function(){
                                      console.log('hey');
                                      console.log(+new Date() - now);
                                      });
                                      x.add(function(){
                                      console.log('ho');
                                      console.log(+new Date() - now);
                                      }, 3000);
                                      x.add(function(){
                                      console.log('bye');
                                      console.log(+new Date() - now);
                                      });

                                      x.run();


                                      Note: using alerts stalls javascript execution till you close the alert.
                                      It might be more code than you asked for, but this is a robust reusable solution.






                                      share|improve this answer




























                                        14














                                        I think you need something like this:



                                        var TimedQueue = function(defaultDelay){
                                        this.queue = ;
                                        this.index = 0;
                                        this.defaultDelay = defaultDelay || 3000;
                                        };

                                        TimedQueue.prototype = {
                                        add: function(fn, delay){
                                        this.queue.push({
                                        fn: fn,
                                        delay: delay
                                        });
                                        },
                                        run: function(index){
                                        (index || index === 0) && (this.index = index);
                                        this.next();
                                        },
                                        next: function(){
                                        var self = this
                                        , i = this.index++
                                        , at = this.queue[i]
                                        , next = this.queue[this.index]
                                        if(!at) return;
                                        at.fn();
                                        next && setTimeout(function(){
                                        self.next();
                                        }, next.delay||this.defaultDelay);
                                        },
                                        reset: function(){
                                        this.index = 0;
                                        }
                                        }


                                        Test code:



                                        var now = +new Date();

                                        var x = new TimedQueue(2000);

                                        x.add(function(){
                                        console.log('hey');
                                        console.log(+new Date() - now);
                                        });
                                        x.add(function(){
                                        console.log('ho');
                                        console.log(+new Date() - now);
                                        }, 3000);
                                        x.add(function(){
                                        console.log('bye');
                                        console.log(+new Date() - now);
                                        });

                                        x.run();


                                        Note: using alerts stalls javascript execution till you close the alert.
                                        It might be more code than you asked for, but this is a robust reusable solution.






                                        share|improve this answer


























                                          14












                                          14








                                          14







                                          I think you need something like this:



                                          var TimedQueue = function(defaultDelay){
                                          this.queue = ;
                                          this.index = 0;
                                          this.defaultDelay = defaultDelay || 3000;
                                          };

                                          TimedQueue.prototype = {
                                          add: function(fn, delay){
                                          this.queue.push({
                                          fn: fn,
                                          delay: delay
                                          });
                                          },
                                          run: function(index){
                                          (index || index === 0) && (this.index = index);
                                          this.next();
                                          },
                                          next: function(){
                                          var self = this
                                          , i = this.index++
                                          , at = this.queue[i]
                                          , next = this.queue[this.index]
                                          if(!at) return;
                                          at.fn();
                                          next && setTimeout(function(){
                                          self.next();
                                          }, next.delay||this.defaultDelay);
                                          },
                                          reset: function(){
                                          this.index = 0;
                                          }
                                          }


                                          Test code:



                                          var now = +new Date();

                                          var x = new TimedQueue(2000);

                                          x.add(function(){
                                          console.log('hey');
                                          console.log(+new Date() - now);
                                          });
                                          x.add(function(){
                                          console.log('ho');
                                          console.log(+new Date() - now);
                                          }, 3000);
                                          x.add(function(){
                                          console.log('bye');
                                          console.log(+new Date() - now);
                                          });

                                          x.run();


                                          Note: using alerts stalls javascript execution till you close the alert.
                                          It might be more code than you asked for, but this is a robust reusable solution.






                                          share|improve this answer













                                          I think you need something like this:



                                          var TimedQueue = function(defaultDelay){
                                          this.queue = ;
                                          this.index = 0;
                                          this.defaultDelay = defaultDelay || 3000;
                                          };

                                          TimedQueue.prototype = {
                                          add: function(fn, delay){
                                          this.queue.push({
                                          fn: fn,
                                          delay: delay
                                          });
                                          },
                                          run: function(index){
                                          (index || index === 0) && (this.index = index);
                                          this.next();
                                          },
                                          next: function(){
                                          var self = this
                                          , i = this.index++
                                          , at = this.queue[i]
                                          , next = this.queue[this.index]
                                          if(!at) return;
                                          at.fn();
                                          next && setTimeout(function(){
                                          self.next();
                                          }, next.delay||this.defaultDelay);
                                          },
                                          reset: function(){
                                          this.index = 0;
                                          }
                                          }


                                          Test code:



                                          var now = +new Date();

                                          var x = new TimedQueue(2000);

                                          x.add(function(){
                                          console.log('hey');
                                          console.log(+new Date() - now);
                                          });
                                          x.add(function(){
                                          console.log('ho');
                                          console.log(+new Date() - now);
                                          }, 3000);
                                          x.add(function(){
                                          console.log('bye');
                                          console.log(+new Date() - now);
                                          });

                                          x.run();


                                          Note: using alerts stalls javascript execution till you close the alert.
                                          It might be more code than you asked for, but this is a robust reusable solution.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Aug 27 '10 at 12:20









                                          BGerrissenBGerrissen

                                          16.8k33338




                                          16.8k33338























                                              13














                                              I would probably use setInteval. Like this,



                                              var period = 1000; // ms
                                              var endTime = 10000; // ms
                                              var counter = 0;
                                              var sleepyAlert = setInterval(function(){
                                              alert('Hello');
                                              if(counter === endTime){
                                              clearInterval(sleepyAlert);
                                              }
                                              counter += period;
                                              }, period);





                                              share|improve this answer



















                                              • 3





                                                SetTimeout is much better than settinterval. google it and you will know

                                                – Abdul Jabbar Dumrai
                                                Feb 23 '14 at 22:26






                                              • 13





                                                I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                                – Marcs
                                                Mar 20 '16 at 22:08











                                              • I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                                – Mateen Ulhaq
                                                Nov 21 '17 at 1:00


















                                              13














                                              I would probably use setInteval. Like this,



                                              var period = 1000; // ms
                                              var endTime = 10000; // ms
                                              var counter = 0;
                                              var sleepyAlert = setInterval(function(){
                                              alert('Hello');
                                              if(counter === endTime){
                                              clearInterval(sleepyAlert);
                                              }
                                              counter += period;
                                              }, period);





                                              share|improve this answer



















                                              • 3





                                                SetTimeout is much better than settinterval. google it and you will know

                                                – Abdul Jabbar Dumrai
                                                Feb 23 '14 at 22:26






                                              • 13





                                                I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                                – Marcs
                                                Mar 20 '16 at 22:08











                                              • I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                                – Mateen Ulhaq
                                                Nov 21 '17 at 1:00
















                                              13












                                              13








                                              13







                                              I would probably use setInteval. Like this,



                                              var period = 1000; // ms
                                              var endTime = 10000; // ms
                                              var counter = 0;
                                              var sleepyAlert = setInterval(function(){
                                              alert('Hello');
                                              if(counter === endTime){
                                              clearInterval(sleepyAlert);
                                              }
                                              counter += period;
                                              }, period);





                                              share|improve this answer













                                              I would probably use setInteval. Like this,



                                              var period = 1000; // ms
                                              var endTime = 10000; // ms
                                              var counter = 0;
                                              var sleepyAlert = setInterval(function(){
                                              alert('Hello');
                                              if(counter === endTime){
                                              clearInterval(sleepyAlert);
                                              }
                                              counter += period;
                                              }, period);






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jun 6 '13 at 13:48









                                              Abel TerefeAbel Terefe

                                              9821413




                                              9821413








                                              • 3





                                                SetTimeout is much better than settinterval. google it and you will know

                                                – Abdul Jabbar Dumrai
                                                Feb 23 '14 at 22:26






                                              • 13





                                                I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                                – Marcs
                                                Mar 20 '16 at 22:08











                                              • I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                                – Mateen Ulhaq
                                                Nov 21 '17 at 1:00
















                                              • 3





                                                SetTimeout is much better than settinterval. google it and you will know

                                                – Abdul Jabbar Dumrai
                                                Feb 23 '14 at 22:26






                                              • 13





                                                I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                                – Marcs
                                                Mar 20 '16 at 22:08











                                              • I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                                – Mateen Ulhaq
                                                Nov 21 '17 at 1:00










                                              3




                                              3





                                              SetTimeout is much better than settinterval. google it and you will know

                                              – Abdul Jabbar Dumrai
                                              Feb 23 '14 at 22:26





                                              SetTimeout is much better than settinterval. google it and you will know

                                              – Abdul Jabbar Dumrai
                                              Feb 23 '14 at 22:26




                                              13




                                              13





                                              I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                              – Marcs
                                              Mar 20 '16 at 22:08





                                              I google it around a little and I found nothing, Why setInterval is bad ? Can you give us a link ? or an example ? Thanks

                                              – Marcs
                                              Mar 20 '16 at 22:08













                                              I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                              – Mateen Ulhaq
                                              Nov 21 '17 at 1:00







                                              I guess the point was that SetInterval() keeps spawning 'threads' even in the event of some error or block.

                                              – Mateen Ulhaq
                                              Nov 21 '17 at 1:00













                                              12














                                              This will work



                                              for (var i = 0; i < 10; i++) {
                                              (function(i) {
                                              setTimeout(function() { console.log(i); }, 100 * i);
                                              })(i);
                                              }


                                              Try this fiddle: https://jsfiddle.net/wgdx8zqq/






                                              share|improve this answer



















                                              • 1





                                                This does trigger all timeout calls near the same time though

                                                – Eddie
                                                Apr 10 '18 at 19:19











                                              • the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                                – ArifMustafa
                                                Oct 20 '18 at 6:55
















                                              12














                                              This will work



                                              for (var i = 0; i < 10; i++) {
                                              (function(i) {
                                              setTimeout(function() { console.log(i); }, 100 * i);
                                              })(i);
                                              }


                                              Try this fiddle: https://jsfiddle.net/wgdx8zqq/






                                              share|improve this answer



















                                              • 1





                                                This does trigger all timeout calls near the same time though

                                                – Eddie
                                                Apr 10 '18 at 19:19











                                              • the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                                – ArifMustafa
                                                Oct 20 '18 at 6:55














                                              12












                                              12








                                              12







                                              This will work



                                              for (var i = 0; i < 10; i++) {
                                              (function(i) {
                                              setTimeout(function() { console.log(i); }, 100 * i);
                                              })(i);
                                              }


                                              Try this fiddle: https://jsfiddle.net/wgdx8zqq/






                                              share|improve this answer













                                              This will work



                                              for (var i = 0; i < 10; i++) {
                                              (function(i) {
                                              setTimeout(function() { console.log(i); }, 100 * i);
                                              })(i);
                                              }


                                              Try this fiddle: https://jsfiddle.net/wgdx8zqq/







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Apr 5 '17 at 6:56









                                              Gsvp NagarajuGsvp Nagaraju

                                              12914




                                              12914








                                              • 1





                                                This does trigger all timeout calls near the same time though

                                                – Eddie
                                                Apr 10 '18 at 19:19











                                              • the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                                – ArifMustafa
                                                Oct 20 '18 at 6:55














                                              • 1





                                                This does trigger all timeout calls near the same time though

                                                – Eddie
                                                Apr 10 '18 at 19:19











                                              • the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                                – ArifMustafa
                                                Oct 20 '18 at 6:55








                                              1




                                              1





                                              This does trigger all timeout calls near the same time though

                                              – Eddie
                                              Apr 10 '18 at 19:19





                                              This does trigger all timeout calls near the same time though

                                              – Eddie
                                              Apr 10 '18 at 19:19













                                              the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                              – ArifMustafa
                                              Oct 20 '18 at 6:55





                                              the only thing I say, I have cracked this way, used $.Deferred but it were some different scenario to let it worked, thumbs to you..!

                                              – ArifMustafa
                                              Oct 20 '18 at 6:55











                                              7














                                              In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.




                                              Generators, a new feature of ECMAScript 6, are functions that can be
                                              paused and resumed. Calling genFunc does not execute it. Instead, it
                                              returns a so-called generator object that lets us control genFunc’s
                                              execution. genFunc() is initially suspended at the beginning of its
                                              body. The method genObj.next() continues the execution of genFunc,
                                              until the next yield.
                                              (Exploring ES6)





                                              Code example:




                                              let arr = [1, 2, 3, 'b'];
                                              let genObj = genFunc();

                                              let val = genObj.next();
                                              console.log(val.value);

                                              let interval = setInterval(() => {
                                              val = genObj.next();

                                              if (val.done) {
                                              clearInterval(interval);
                                              } else {
                                              console.log(val.value);
                                              }
                                              }, 1000);

                                              function* genFunc() {
                                              for(let item of arr) {
                                              yield item;
                                              }
                                              }





                                              So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).






                                              share|improve this answer




























                                                7














                                                In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.




                                                Generators, a new feature of ECMAScript 6, are functions that can be
                                                paused and resumed. Calling genFunc does not execute it. Instead, it
                                                returns a so-called generator object that lets us control genFunc’s
                                                execution. genFunc() is initially suspended at the beginning of its
                                                body. The method genObj.next() continues the execution of genFunc,
                                                until the next yield.
                                                (Exploring ES6)





                                                Code example:




                                                let arr = [1, 2, 3, 'b'];
                                                let genObj = genFunc();

                                                let val = genObj.next();
                                                console.log(val.value);

                                                let interval = setInterval(() => {
                                                val = genObj.next();

                                                if (val.done) {
                                                clearInterval(interval);
                                                } else {
                                                console.log(val.value);
                                                }
                                                }, 1000);

                                                function* genFunc() {
                                                for(let item of arr) {
                                                yield item;
                                                }
                                                }





                                                So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).






                                                share|improve this answer


























                                                  7












                                                  7








                                                  7







                                                  In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.




                                                  Generators, a new feature of ECMAScript 6, are functions that can be
                                                  paused and resumed. Calling genFunc does not execute it. Instead, it
                                                  returns a so-called generator object that lets us control genFunc’s
                                                  execution. genFunc() is initially suspended at the beginning of its
                                                  body. The method genObj.next() continues the execution of genFunc,
                                                  until the next yield.
                                                  (Exploring ES6)





                                                  Code example:




                                                  let arr = [1, 2, 3, 'b'];
                                                  let genObj = genFunc();

                                                  let val = genObj.next();
                                                  console.log(val.value);

                                                  let interval = setInterval(() => {
                                                  val = genObj.next();

                                                  if (val.done) {
                                                  clearInterval(interval);
                                                  } else {
                                                  console.log(val.value);
                                                  }
                                                  }, 1000);

                                                  function* genFunc() {
                                                  for(let item of arr) {
                                                  yield item;
                                                  }
                                                  }





                                                  So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).






                                                  share|improve this answer













                                                  In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.




                                                  Generators, a new feature of ECMAScript 6, are functions that can be
                                                  paused and resumed. Calling genFunc does not execute it. Instead, it
                                                  returns a so-called generator object that lets us control genFunc’s
                                                  execution. genFunc() is initially suspended at the beginning of its
                                                  body. The method genObj.next() continues the execution of genFunc,
                                                  until the next yield.
                                                  (Exploring ES6)





                                                  Code example:




                                                  let arr = [1, 2, 3, 'b'];
                                                  let genObj = genFunc();

                                                  let val = genObj.next();
                                                  console.log(val.value);

                                                  let interval = setInterval(() => {
                                                  val = genObj.next();

                                                  if (val.done) {
                                                  clearInterval(interval);
                                                  } else {
                                                  console.log(val.value);
                                                  }
                                                  }, 1000);

                                                  function* genFunc() {
                                                  for(let item of arr) {
                                                  yield item;
                                                  }
                                                  }





                                                  So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).






                                                  let arr = [1, 2, 3, 'b'];
                                                  let genObj = genFunc();

                                                  let val = genObj.next();
                                                  console.log(val.value);

                                                  let interval = setInterval(() => {
                                                  val = genObj.next();

                                                  if (val.done) {
                                                  clearInterval(interval);
                                                  } else {
                                                  console.log(val.value);
                                                  }
                                                  }, 1000);

                                                  function* genFunc() {
                                                  for(let item of arr) {
                                                  yield item;
                                                  }
                                                  }





                                                  let arr = [1, 2, 3, 'b'];
                                                  let genObj = genFunc();

                                                  let val = genObj.next();
                                                  console.log(val.value);

                                                  let interval = setInterval(() => {
                                                  val = genObj.next();

                                                  if (val.done) {
                                                  clearInterval(interval);
                                                  } else {
                                                  console.log(val.value);
                                                  }
                                                  }, 1000);

                                                  function* genFunc() {
                                                  for(let item of arr) {
                                                  yield item;
                                                  }
                                                  }






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Oct 7 '15 at 15:26









                                                  Itay RadotzkiItay Radotzki

                                                  797179




                                                  797179























                                                      4














                                                      I do this with Bluebird’s Promise.delay and recursion.






                                                      function myLoop(i) {
                                                      return Promise.delay(1000)
                                                      .then(function() {
                                                      if (i > 0) {
                                                      alert('hello');
                                                      return myLoop(i -= 1);
                                                      }
                                                      });
                                                      }

                                                      myLoop(3);

                                                      <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>








                                                      share|improve this answer






























                                                        4














                                                        I do this with Bluebird’s Promise.delay and recursion.






                                                        function myLoop(i) {
                                                        return Promise.delay(1000)
                                                        .then(function() {
                                                        if (i > 0) {
                                                        alert('hello');
                                                        return myLoop(i -= 1);
                                                        }
                                                        });
                                                        }

                                                        myLoop(3);

                                                        <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>








                                                        share|improve this answer




























                                                          4












                                                          4








                                                          4







                                                          I do this with Bluebird’s Promise.delay and recursion.






                                                          function myLoop(i) {
                                                          return Promise.delay(1000)
                                                          .then(function() {
                                                          if (i > 0) {
                                                          alert('hello');
                                                          return myLoop(i -= 1);
                                                          }
                                                          });
                                                          }

                                                          myLoop(3);

                                                          <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>








                                                          share|improve this answer















                                                          I do this with Bluebird’s Promise.delay and recursion.






                                                          function myLoop(i) {
                                                          return Promise.delay(1000)
                                                          .then(function() {
                                                          if (i > 0) {
                                                          alert('hello');
                                                          return myLoop(i -= 1);
                                                          }
                                                          });
                                                          }

                                                          myLoop(3);

                                                          <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>








                                                          function myLoop(i) {
                                                          return Promise.delay(1000)
                                                          .then(function() {
                                                          if (i > 0) {
                                                          alert('hello');
                                                          return myLoop(i -= 1);
                                                          }
                                                          });
                                                          }

                                                          myLoop(3);

                                                          <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>





                                                          function myLoop(i) {
                                                          return Promise.delay(1000)
                                                          .then(function() {
                                                          if (i > 0) {
                                                          alert('hello');
                                                          return myLoop(i -= 1);
                                                          }
                                                          });
                                                          }

                                                          myLoop(3);

                                                          <script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jun 10 '18 at 23:50









                                                          Xufox

                                                          10.3k63151




                                                          10.3k63151










                                                          answered Feb 2 '15 at 9:06









                                                          Dave BryandDave Bryand

                                                          446411




                                                          446411























                                                              3














                                                              Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:



                                                              function timeout(range, time, callback){
                                                              var i = range[0];
                                                              callback(i);
                                                              Loop();
                                                              function Loop(){
                                                              setTimeout(function(){
                                                              i++;
                                                              if (i<range[1]){
                                                              callback(i);
                                                              Loop();
                                                              }
                                                              }, time*1000)
                                                              }
                                                              }


                                                              For example:



                                                              //This function prints the loop number every second
                                                              timeout([0, 5], 1, function(i){
                                                              console.log(i);
                                                              });


                                                              Would be equivalent to:



                                                              //This function prints the loop number instantly
                                                              for (var i = 0; i<5; i++){
                                                              console.log(i);
                                                              }





                                                              share|improve this answer






























                                                                3














                                                                Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:



                                                                function timeout(range, time, callback){
                                                                var i = range[0];
                                                                callback(i);
                                                                Loop();
                                                                function Loop(){
                                                                setTimeout(function(){
                                                                i++;
                                                                if (i<range[1]){
                                                                callback(i);
                                                                Loop();
                                                                }
                                                                }, time*1000)
                                                                }
                                                                }


                                                                For example:



                                                                //This function prints the loop number every second
                                                                timeout([0, 5], 1, function(i){
                                                                console.log(i);
                                                                });


                                                                Would be equivalent to:



                                                                //This function prints the loop number instantly
                                                                for (var i = 0; i<5; i++){
                                                                console.log(i);
                                                                }





                                                                share|improve this answer




























                                                                  3












                                                                  3








                                                                  3







                                                                  Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:



                                                                  function timeout(range, time, callback){
                                                                  var i = range[0];
                                                                  callback(i);
                                                                  Loop();
                                                                  function Loop(){
                                                                  setTimeout(function(){
                                                                  i++;
                                                                  if (i<range[1]){
                                                                  callback(i);
                                                                  Loop();
                                                                  }
                                                                  }, time*1000)
                                                                  }
                                                                  }


                                                                  For example:



                                                                  //This function prints the loop number every second
                                                                  timeout([0, 5], 1, function(i){
                                                                  console.log(i);
                                                                  });


                                                                  Would be equivalent to:



                                                                  //This function prints the loop number instantly
                                                                  for (var i = 0; i<5; i++){
                                                                  console.log(i);
                                                                  }





                                                                  share|improve this answer















                                                                  Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:



                                                                  function timeout(range, time, callback){
                                                                  var i = range[0];
                                                                  callback(i);
                                                                  Loop();
                                                                  function Loop(){
                                                                  setTimeout(function(){
                                                                  i++;
                                                                  if (i<range[1]){
                                                                  callback(i);
                                                                  Loop();
                                                                  }
                                                                  }, time*1000)
                                                                  }
                                                                  }


                                                                  For example:



                                                                  //This function prints the loop number every second
                                                                  timeout([0, 5], 1, function(i){
                                                                  console.log(i);
                                                                  });


                                                                  Would be equivalent to:



                                                                  //This function prints the loop number instantly
                                                                  for (var i = 0; i<5; i++){
                                                                  console.log(i);
                                                                  }






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Aug 4 '16 at 17:02

























                                                                  answered Nov 6 '15 at 12:57









                                                                  D SleeD Slee

                                                                  57036




                                                                  57036























                                                                      2














                                                                      You can use RxJS interval operator. Interval emits integer every x number of seconds, and take is specify number of times it has to emit numberss






                                                                      Rx.Observable
                                                                      .interval(1000)
                                                                      .take(10)
                                                                      .subscribe((x) => console.log(x))

                                                                      <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>








                                                                      share|improve this answer




























                                                                        2














                                                                        You can use RxJS interval operator. Interval emits integer every x number of seconds, and take is specify number of times it has to emit numberss






                                                                        Rx.Observable
                                                                        .interval(1000)
                                                                        .take(10)
                                                                        .subscribe((x) => console.log(x))

                                                                        <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>








                                                                        share|improve this answer


























                                                                          2












                                                                          2








                                                                          2







                                                                          You can use RxJS interval operator. Interval emits integer every x number of seconds, and take is specify number of times it has to emit numberss






                                                                          Rx.Observable
                                                                          .interval(1000)
                                                                          .take(10)
                                                                          .subscribe((x) => console.log(x))

                                                                          <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>








                                                                          share|improve this answer













                                                                          You can use RxJS interval operator. Interval emits integer every x number of seconds, and take is specify number of times it has to emit numberss






                                                                          Rx.Observable
                                                                          .interval(1000)
                                                                          .take(10)
                                                                          .subscribe((x) => console.log(x))

                                                                          <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>








                                                                          Rx.Observable
                                                                          .interval(1000)
                                                                          .take(10)
                                                                          .subscribe((x) => console.log(x))

                                                                          <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>





                                                                          Rx.Observable
                                                                          .interval(1000)
                                                                          .take(10)
                                                                          .subscribe((x) => console.log(x))

                                                                          <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>






                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Jun 23 '16 at 19:59









                                                                          Vlad BezdenVlad Bezden

                                                                          30.7k10135115




                                                                          30.7k10135115























                                                                              1

















                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);





                                                                              A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:



                                                                              First let's define some essential variables:



                                                                              var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 3000;


                                                                              Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:



                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }


                                                                              Self-executing version



                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);


                                                                              Functional version



                                                                              function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              }

                                                                              forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it





                                                                              share|improve this answer
























                                                                              • nice one and how do I pass data to the function without a global variable

                                                                                – Sundara Prabu
                                                                                May 29 '17 at 17:54
















                                                                              1

















                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);





                                                                              A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:



                                                                              First let's define some essential variables:



                                                                              var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 3000;


                                                                              Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:



                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }


                                                                              Self-executing version



                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);


                                                                              Functional version



                                                                              function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              }

                                                                              forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it





                                                                              share|improve this answer
























                                                                              • nice one and how do I pass data to the function without a global variable

                                                                                – Sundara Prabu
                                                                                May 29 '17 at 17:54














                                                                              1












                                                                              1








                                                                              1










                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);





                                                                              A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:



                                                                              First let's define some essential variables:



                                                                              var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 3000;


                                                                              Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:



                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }


                                                                              Self-executing version



                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);


                                                                              Functional version



                                                                              function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              }

                                                                              forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it





                                                                              share|improve this answer
















                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);





                                                                              A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:



                                                                              First let's define some essential variables:



                                                                              var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 3000;


                                                                              Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:



                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }


                                                                              Self-executing version



                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);


                                                                              Functional version



                                                                              function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function () {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              }

                                                                              forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it





                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);





                                                                                  var startIndex = 0;
                                                                              var data = [1, 2, 3];
                                                                              var timeout = 1000;

                                                                              function functionToRun(i, length) {
                                                                              alert(data[i]);
                                                                              }

                                                                              (function forWithDelay(i, length, fn, delay) {
                                                                              setTimeout(function() {
                                                                              fn(i, length);
                                                                              i++;
                                                                              if (i < length) {
                                                                              forWithDelay(i, length, fn, delay);
                                                                              }
                                                                              }, delay);
                                                                              })(startIndex, data.length, functionToRun, timeout);






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Mar 10 '16 at 15:22









                                                                              Jasdeep KhalsaJasdeep Khalsa

                                                                              3,36073055




                                                                              3,36073055













                                                                              • nice one and how do I pass data to the function without a global variable

                                                                                – Sundara Prabu
                                                                                May 29 '17 at 17:54



















                                                                              • nice one and how do I pass data to the function without a global variable

                                                                                – Sundara Prabu
                                                                                May 29 '17 at 17:54

















                                                                              nice one and how do I pass data to the function without a global variable

                                                                              – Sundara Prabu
                                                                              May 29 '17 at 17:54





                                                                              nice one and how do I pass data to the function without a global variable

                                                                              – Sundara Prabu
                                                                              May 29 '17 at 17:54











                                                                              0














                                                                              /* 
                                                                              Use Recursive and setTimeout
                                                                              call below function will run loop loopFunctionNeedCheck until
                                                                              conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
                                                                              reRunAfterMs miliseconds and continue loop
                                                                              tested code, thanks
                                                                              */

                                                                              function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                                                                              loopFunctionNeedCheck) {
                                                                              loopFunctionNeedCheck();
                                                                              var result = conditionCheckAfterRunFn();
                                                                              //check after run
                                                                              if (!result) {
                                                                              setTimeout(function () {
                                                                              functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                                                                              }, reRunAfterMs);
                                                                              }
                                                                              else console.log("completed, thanks");
                                                                              //if you need call a function after completed add code call callback in here
                                                                              }

                                                                              //passing-parameters-to-a-callback-function
                                                                              // From Prototype.js
                                                                              if (!Function.prototype.bind) { // check if native implementation available
                                                                              Function.prototype.bind = function () {
                                                                              var fn = this, args = Array.prototype.slice.call(arguments),
                                                                              object = args.shift();
                                                                              return function () {
                                                                              return fn.apply(object,
                                                                              args.concat(Array.prototype.slice.call(arguments)));
                                                                              };
                                                                              };
                                                                              }

                                                                              //test code:
                                                                              var result = 0;
                                                                              console.log("---> init result is " + result);
                                                                              var functionNeedRun = function (step) {
                                                                              result+=step;
                                                                              console.log("current result is " + result);
                                                                              }
                                                                              var checkResultFunction = function () {
                                                                              return result==100;
                                                                              }

                                                                              //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
                                                                              functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));

                                                                              //result log from console:
                                                                              /*
                                                                              ---> init result is 0
                                                                              current result is 5
                                                                              undefined
                                                                              current result is 10
                                                                              current result is 15
                                                                              current result is 20
                                                                              current result is 25
                                                                              current result is 30
                                                                              current result is 35
                                                                              current result is 40
                                                                              current result is 45
                                                                              current result is 50
                                                                              current result is 55
                                                                              current result is 60
                                                                              current result is 65
                                                                              current result is 70
                                                                              current result is 75
                                                                              current result is 80
                                                                              current result is 85
                                                                              current result is 90
                                                                              current result is 95
                                                                              current result is 100
                                                                              completed, thanks
                                                                              */





                                                                              share|improve this answer



















                                                                              • 7





                                                                                Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                                – Mark Walters
                                                                                Nov 26 '13 at 15:11
















                                                                              0














                                                                              /* 
                                                                              Use Recursive and setTimeout
                                                                              call below function will run loop loopFunctionNeedCheck until
                                                                              conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
                                                                              reRunAfterMs miliseconds and continue loop
                                                                              tested code, thanks
                                                                              */

                                                                              function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                                                                              loopFunctionNeedCheck) {
                                                                              loopFunctionNeedCheck();
                                                                              var result = conditionCheckAfterRunFn();
                                                                              //check after run
                                                                              if (!result) {
                                                                              setTimeout(function () {
                                                                              functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                                                                              }, reRunAfterMs);
                                                                              }
                                                                              else console.log("completed, thanks");
                                                                              //if you need call a function after completed add code call callback in here
                                                                              }

                                                                              //passing-parameters-to-a-callback-function
                                                                              // From Prototype.js
                                                                              if (!Function.prototype.bind) { // check if native implementation available
                                                                              Function.prototype.bind = function () {
                                                                              var fn = this, args = Array.prototype.slice.call(arguments),
                                                                              object = args.shift();
                                                                              return function () {
                                                                              return fn.apply(object,
                                                                              args.concat(Array.prototype.slice.call(arguments)));
                                                                              };
                                                                              };
                                                                              }

                                                                              //test code:
                                                                              var result = 0;
                                                                              console.log("---> init result is " + result);
                                                                              var functionNeedRun = function (step) {
                                                                              result+=step;
                                                                              console.log("current result is " + result);
                                                                              }
                                                                              var checkResultFunction = function () {
                                                                              return result==100;
                                                                              }

                                                                              //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
                                                                              functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));

                                                                              //result log from console:
                                                                              /*
                                                                              ---> init result is 0
                                                                              current result is 5
                                                                              undefined
                                                                              current result is 10
                                                                              current result is 15
                                                                              current result is 20
                                                                              current result is 25
                                                                              current result is 30
                                                                              current result is 35
                                                                              current result is 40
                                                                              current result is 45
                                                                              current result is 50
                                                                              current result is 55
                                                                              current result is 60
                                                                              current result is 65
                                                                              current result is 70
                                                                              current result is 75
                                                                              current result is 80
                                                                              current result is 85
                                                                              current result is 90
                                                                              current result is 95
                                                                              current result is 100
                                                                              completed, thanks
                                                                              */





                                                                              share|improve this answer



















                                                                              • 7





                                                                                Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                                – Mark Walters
                                                                                Nov 26 '13 at 15:11














                                                                              0












                                                                              0








                                                                              0







                                                                              /* 
                                                                              Use Recursive and setTimeout
                                                                              call below function will run loop loopFunctionNeedCheck until
                                                                              conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
                                                                              reRunAfterMs miliseconds and continue loop
                                                                              tested code, thanks
                                                                              */

                                                                              function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                                                                              loopFunctionNeedCheck) {
                                                                              loopFunctionNeedCheck();
                                                                              var result = conditionCheckAfterRunFn();
                                                                              //check after run
                                                                              if (!result) {
                                                                              setTimeout(function () {
                                                                              functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                                                                              }, reRunAfterMs);
                                                                              }
                                                                              else console.log("completed, thanks");
                                                                              //if you need call a function after completed add code call callback in here
                                                                              }

                                                                              //passing-parameters-to-a-callback-function
                                                                              // From Prototype.js
                                                                              if (!Function.prototype.bind) { // check if native implementation available
                                                                              Function.prototype.bind = function () {
                                                                              var fn = this, args = Array.prototype.slice.call(arguments),
                                                                              object = args.shift();
                                                                              return function () {
                                                                              return fn.apply(object,
                                                                              args.concat(Array.prototype.slice.call(arguments)));
                                                                              };
                                                                              };
                                                                              }

                                                                              //test code:
                                                                              var result = 0;
                                                                              console.log("---> init result is " + result);
                                                                              var functionNeedRun = function (step) {
                                                                              result+=step;
                                                                              console.log("current result is " + result);
                                                                              }
                                                                              var checkResultFunction = function () {
                                                                              return result==100;
                                                                              }

                                                                              //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
                                                                              functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));

                                                                              //result log from console:
                                                                              /*
                                                                              ---> init result is 0
                                                                              current result is 5
                                                                              undefined
                                                                              current result is 10
                                                                              current result is 15
                                                                              current result is 20
                                                                              current result is 25
                                                                              current result is 30
                                                                              current result is 35
                                                                              current result is 40
                                                                              current result is 45
                                                                              current result is 50
                                                                              current result is 55
                                                                              current result is 60
                                                                              current result is 65
                                                                              current result is 70
                                                                              current result is 75
                                                                              current result is 80
                                                                              current result is 85
                                                                              current result is 90
                                                                              current result is 95
                                                                              current result is 100
                                                                              completed, thanks
                                                                              */





                                                                              share|improve this answer













                                                                              /* 
                                                                              Use Recursive and setTimeout
                                                                              call below function will run loop loopFunctionNeedCheck until
                                                                              conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
                                                                              reRunAfterMs miliseconds and continue loop
                                                                              tested code, thanks
                                                                              */

                                                                              function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                                                                              loopFunctionNeedCheck) {
                                                                              loopFunctionNeedCheck();
                                                                              var result = conditionCheckAfterRunFn();
                                                                              //check after run
                                                                              if (!result) {
                                                                              setTimeout(function () {
                                                                              functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                                                                              }, reRunAfterMs);
                                                                              }
                                                                              else console.log("completed, thanks");
                                                                              //if you need call a function after completed add code call callback in here
                                                                              }

                                                                              //passing-parameters-to-a-callback-function
                                                                              // From Prototype.js
                                                                              if (!Function.prototype.bind) { // check if native implementation available
                                                                              Function.prototype.bind = function () {
                                                                              var fn = this, args = Array.prototype.slice.call(arguments),
                                                                              object = args.shift();
                                                                              return function () {
                                                                              return fn.apply(object,
                                                                              args.concat(Array.prototype.slice.call(arguments)));
                                                                              };
                                                                              };
                                                                              }

                                                                              //test code:
                                                                              var result = 0;
                                                                              console.log("---> init result is " + result);
                                                                              var functionNeedRun = function (step) {
                                                                              result+=step;
                                                                              console.log("current result is " + result);
                                                                              }
                                                                              var checkResultFunction = function () {
                                                                              return result==100;
                                                                              }

                                                                              //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
                                                                              functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));

                                                                              //result log from console:
                                                                              /*
                                                                              ---> init result is 0
                                                                              current result is 5
                                                                              undefined
                                                                              current result is 10
                                                                              current result is 15
                                                                              current result is 20
                                                                              current result is 25
                                                                              current result is 30
                                                                              current result is 35
                                                                              current result is 40
                                                                              current result is 45
                                                                              current result is 50
                                                                              current result is 55
                                                                              current result is 60
                                                                              current result is 65
                                                                              current result is 70
                                                                              current result is 75
                                                                              current result is 80
                                                                              current result is 85
                                                                              current result is 90
                                                                              current result is 95
                                                                              current result is 100
                                                                              completed, thanks
                                                                              */






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Oct 24 '13 at 2:51









                                                                              user2913925user2913925

                                                                              29




                                                                              29








                                                                              • 7





                                                                                Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                                – Mark Walters
                                                                                Nov 26 '13 at 15:11














                                                                              • 7





                                                                                Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                                – Mark Walters
                                                                                Nov 26 '13 at 15:11








                                                                              7




                                                                              7





                                                                              Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                              – Mark Walters
                                                                              Nov 26 '13 at 15:11





                                                                              Your function names are horrendous, that's the main reason why this code is so hard to read.

                                                                              – Mark Walters
                                                                              Nov 26 '13 at 15:11











                                                                              0














                                                                              Here is how I created an infinite loop with a delay that breaks on a certain condition:



                                                                                // Now continuously check the app status until it's completed, 
                                                                              // failed or times out. The isFinished() will throw exception if
                                                                              // there is a failure.
                                                                              while (true) {
                                                                              let status = await this.api.getStatus(appId);
                                                                              if (isFinished(status)) {
                                                                              break;
                                                                              } else {
                                                                              // Delay before running the next loop iteration:
                                                                              await new Promise(resolve => setTimeout(resolve, 3000));
                                                                              }
                                                                              }


                                                                              The key here is to create a new Promise that resolves by timeout, and to await for its resolution.



                                                                              Obviously you need async/await support for that. Works in Node 8.






                                                                              share|improve this answer






























                                                                                0














                                                                                Here is how I created an infinite loop with a delay that breaks on a certain condition:



                                                                                  // Now continuously check the app status until it's completed, 
                                                                                // failed or times out. The isFinished() will throw exception if
                                                                                // there is a failure.
                                                                                while (true) {
                                                                                let status = await this.api.getStatus(appId);
                                                                                if (isFinished(status)) {
                                                                                break;
                                                                                } else {
                                                                                // Delay before running the next loop iteration:
                                                                                await new Promise(resolve => setTimeout(resolve, 3000));
                                                                                }
                                                                                }


                                                                                The key here is to create a new Promise that resolves by timeout, and to await for its resolution.



                                                                                Obviously you need async/await support for that. Works in Node 8.






                                                                                share|improve this answer




























                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  Here is how I created an infinite loop with a delay that breaks on a certain condition:



                                                                                    // Now continuously check the app status until it's completed, 
                                                                                  // failed or times out. The isFinished() will throw exception if
                                                                                  // there is a failure.
                                                                                  while (true) {
                                                                                  let status = await this.api.getStatus(appId);
                                                                                  if (isFinished(status)) {
                                                                                  break;
                                                                                  } else {
                                                                                  // Delay before running the next loop iteration:
                                                                                  await new Promise(resolve => setTimeout(resolve, 3000));
                                                                                  }
                                                                                  }


                                                                                  The key here is to create a new Promise that resolves by timeout, and to await for its resolution.



                                                                                  Obviously you need async/await support for that. Works in Node 8.






                                                                                  share|improve this answer















                                                                                  Here is how I created an infinite loop with a delay that breaks on a certain condition:



                                                                                    // Now continuously check the app status until it's completed, 
                                                                                  // failed or times out. The isFinished() will throw exception if
                                                                                  // there is a failure.
                                                                                  while (true) {
                                                                                  let status = await this.api.getStatus(appId);
                                                                                  if (isFinished(status)) {
                                                                                  break;
                                                                                  } else {
                                                                                  // Delay before running the next loop iteration:
                                                                                  await new Promise(resolve => setTimeout(resolve, 3000));
                                                                                  }
                                                                                  }


                                                                                  The key here is to create a new Promise that resolves by timeout, and to await for its resolution.



                                                                                  Obviously you need async/await support for that. Works in Node 8.







                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Sep 27 '17 at 17:21

























                                                                                  answered Sep 27 '17 at 16:58









                                                                                  K48K48

                                                                                  5,67494197




                                                                                  5,67494197























                                                                                      0














                                                                                      for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).



                                                                                              function iAsk(lvl){
                                                                                      var i=0;
                                                                                      var intr =setInterval(function(){ // start the loop
                                                                                      i++; // increment it
                                                                                      if(i>lvl){ // check if the end round reached.
                                                                                      clearInterval(intr);
                                                                                      return;
                                                                                      }
                                                                                      setTimeout(function(){
                                                                                      $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                                                                                      },50);
                                                                                      setTimeout(function(){
                                                                                      // do another bla bla bla after 100 millisecond.
                                                                                      seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                                                                                      $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                                                                                      $("#d"+seq[i-1]).prop("src",pGif);
                                                                                      var d =document.getElementById('aud');
                                                                                      d.play();
                                                                                      },100);
                                                                                      setTimeout(function(){
                                                                                      // keep adding bla bla bla till you done :)
                                                                                      $("#d"+seq[i-1]).prop("src",pPng);
                                                                                      },900);
                                                                                      },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                                                                                      }


                                                                                      PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.



                                                                                      PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..






                                                                                      share|improve this answer




























                                                                                        0














                                                                                        for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).



                                                                                                function iAsk(lvl){
                                                                                        var i=0;
                                                                                        var intr =setInterval(function(){ // start the loop
                                                                                        i++; // increment it
                                                                                        if(i>lvl){ // check if the end round reached.
                                                                                        clearInterval(intr);
                                                                                        return;
                                                                                        }
                                                                                        setTimeout(function(){
                                                                                        $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                                                                                        },50);
                                                                                        setTimeout(function(){
                                                                                        // do another bla bla bla after 100 millisecond.
                                                                                        seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                                                                                        $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                                                                                        $("#d"+seq[i-1]).prop("src",pGif);
                                                                                        var d =document.getElementById('aud');
                                                                                        d.play();
                                                                                        },100);
                                                                                        setTimeout(function(){
                                                                                        // keep adding bla bla bla till you done :)
                                                                                        $("#d"+seq[i-1]).prop("src",pPng);
                                                                                        },900);
                                                                                        },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                                                                                        }


                                                                                        PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.



                                                                                        PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..






                                                                                        share|improve this answer


























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).



                                                                                                  function iAsk(lvl){
                                                                                          var i=0;
                                                                                          var intr =setInterval(function(){ // start the loop
                                                                                          i++; // increment it
                                                                                          if(i>lvl){ // check if the end round reached.
                                                                                          clearInterval(intr);
                                                                                          return;
                                                                                          }
                                                                                          setTimeout(function(){
                                                                                          $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                                                                                          },50);
                                                                                          setTimeout(function(){
                                                                                          // do another bla bla bla after 100 millisecond.
                                                                                          seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                                                                                          $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                                                                                          $("#d"+seq[i-1]).prop("src",pGif);
                                                                                          var d =document.getElementById('aud');
                                                                                          d.play();
                                                                                          },100);
                                                                                          setTimeout(function(){
                                                                                          // keep adding bla bla bla till you done :)
                                                                                          $("#d"+seq[i-1]).prop("src",pPng);
                                                                                          },900);
                                                                                          },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                                                                                          }


                                                                                          PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.



                                                                                          PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..






                                                                                          share|improve this answer













                                                                                          for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).



                                                                                                  function iAsk(lvl){
                                                                                          var i=0;
                                                                                          var intr =setInterval(function(){ // start the loop
                                                                                          i++; // increment it
                                                                                          if(i>lvl){ // check if the end round reached.
                                                                                          clearInterval(intr);
                                                                                          return;
                                                                                          }
                                                                                          setTimeout(function(){
                                                                                          $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                                                                                          },50);
                                                                                          setTimeout(function(){
                                                                                          // do another bla bla bla after 100 millisecond.
                                                                                          seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                                                                                          $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                                                                                          $("#d"+seq[i-1]).prop("src",pGif);
                                                                                          var d =document.getElementById('aud');
                                                                                          d.play();
                                                                                          },100);
                                                                                          setTimeout(function(){
                                                                                          // keep adding bla bla bla till you done :)
                                                                                          $("#d"+seq[i-1]).prop("src",pPng);
                                                                                          },900);
                                                                                          },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                                                                                          }


                                                                                          PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.



                                                                                          PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Dec 1 '17 at 8:27









                                                                                          Mohamed AbulnasrMohamed Abulnasr

                                                                                          327311




                                                                                          327311























                                                                                              0

















                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>








                                                                                              share|improve this answer



















                                                                                              • 1





                                                                                                Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                                – Hexfire
                                                                                                Jan 23 '18 at 7:47






                                                                                              • 1





                                                                                                Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                                – WhatsThePoint
                                                                                                Jan 23 '18 at 7:58
















                                                                                              0

















                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>








                                                                                              share|improve this answer



















                                                                                              • 1





                                                                                                Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                                – Hexfire
                                                                                                Jan 23 '18 at 7:47






                                                                                              • 1





                                                                                                Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                                – WhatsThePoint
                                                                                                Jan 23 '18 at 7:58














                                                                                              0












                                                                                              0








                                                                                              0










                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>








                                                                                              share|improve this answer
















                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>








                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>





                                                                                              <!DOCTYPE html>
                                                                                              <html>
                                                                                              <body>

                                                                                              <button onclick="myFunction()">Try it</button>

                                                                                              <p id="demo"></p>

                                                                                              <script>
                                                                                              function myFunction() {
                                                                                              for(var i=0; i<5; i++) {
                                                                                              var sno = i+1;
                                                                                              (function myLoop (i) {
                                                                                              setTimeout(function () {
                                                                                              alert(i); // Do your function here
                                                                                              }, 1000*i);
                                                                                              })(sno);
                                                                                              }
                                                                                              }
                                                                                              </script>

                                                                                              </body>
                                                                                              </html>






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Jan 23 '18 at 7:40









                                                                                              Boginaathan MBoginaathan M

                                                                                              91




                                                                                              91








                                                                                              • 1





                                                                                                Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                                – Hexfire
                                                                                                Jan 23 '18 at 7:47






                                                                                              • 1





                                                                                                Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                                – WhatsThePoint
                                                                                                Jan 23 '18 at 7:58














                                                                                              • 1





                                                                                                Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                                – Hexfire
                                                                                                Jan 23 '18 at 7:47






                                                                                              • 1





                                                                                                Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                                – WhatsThePoint
                                                                                                Jan 23 '18 at 7:58








                                                                                              1




                                                                                              1





                                                                                              Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                              – Hexfire
                                                                                              Jan 23 '18 at 7:47





                                                                                              Please always provide at least brief description to your code snippets, at least for others to be sure that you address the question.

                                                                                              – Hexfire
                                                                                              Jan 23 '18 at 7:47




                                                                                              1




                                                                                              1





                                                                                              Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                              – WhatsThePoint
                                                                                              Jan 23 '18 at 7:58





                                                                                              Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written

                                                                                              – WhatsThePoint
                                                                                              Jan 23 '18 at 7:58











                                                                                              0














                                                                                              Simple implementation of showing a piece of text every two seconds as long the loop is running.



                                                                                              for (var i = 0; i < foo.length; i++) {
                                                                                              setInterval(function(){
                                                                                              console.log("I will appear every 2 seconds");
                                                                                              }, 2000);
                                                                                              break;
                                                                                              };





                                                                                              share|improve this answer




























                                                                                                0














                                                                                                Simple implementation of showing a piece of text every two seconds as long the loop is running.



                                                                                                for (var i = 0; i < foo.length; i++) {
                                                                                                setInterval(function(){
                                                                                                console.log("I will appear every 2 seconds");
                                                                                                }, 2000);
                                                                                                break;
                                                                                                };





                                                                                                share|improve this answer


























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  Simple implementation of showing a piece of text every two seconds as long the loop is running.



                                                                                                  for (var i = 0; i < foo.length; i++) {
                                                                                                  setInterval(function(){
                                                                                                  console.log("I will appear every 2 seconds");
                                                                                                  }, 2000);
                                                                                                  break;
                                                                                                  };





                                                                                                  share|improve this answer













                                                                                                  Simple implementation of showing a piece of text every two seconds as long the loop is running.



                                                                                                  for (var i = 0; i < foo.length; i++) {
                                                                                                  setInterval(function(){
                                                                                                  console.log("I will appear every 2 seconds");
                                                                                                  }, 2000);
                                                                                                  break;
                                                                                                  };






                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Nov 14 '18 at 16:26









                                                                                                  squeekyDavesqueekyDave

                                                                                                  489217




                                                                                                  489217























                                                                                                      0














                                                                                                      To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:



                                                                                                      var looper = async function () {
                                                                                                      for (var start = 1; start < 10; start++) {
                                                                                                      await new Promise(function (resolve, reject) {
                                                                                                      setTimeout(function () {
                                                                                                      console.log("iteration: " + start.toString());
                                                                                                      resolve(true);
                                                                                                      }, 1000);
                                                                                                      });
                                                                                                      }
                                                                                                      return true;
                                                                                                      }


                                                                                                      And then you call run it like so:



                                                                                                      looper().then(function(){
                                                                                                      console.log("DONE!")
                                                                                                      });


                                                                                                      Please take some time to get a good understanding of asynchronous programming.






                                                                                                      share|improve this answer




























                                                                                                        0














                                                                                                        To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:



                                                                                                        var looper = async function () {
                                                                                                        for (var start = 1; start < 10; start++) {
                                                                                                        await new Promise(function (resolve, reject) {
                                                                                                        setTimeout(function () {
                                                                                                        console.log("iteration: " + start.toString());
                                                                                                        resolve(true);
                                                                                                        }, 1000);
                                                                                                        });
                                                                                                        }
                                                                                                        return true;
                                                                                                        }


                                                                                                        And then you call run it like so:



                                                                                                        looper().then(function(){
                                                                                                        console.log("DONE!")
                                                                                                        });


                                                                                                        Please take some time to get a good understanding of asynchronous programming.






                                                                                                        share|improve this answer


























                                                                                                          0












                                                                                                          0








                                                                                                          0







                                                                                                          To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:



                                                                                                          var looper = async function () {
                                                                                                          for (var start = 1; start < 10; start++) {
                                                                                                          await new Promise(function (resolve, reject) {
                                                                                                          setTimeout(function () {
                                                                                                          console.log("iteration: " + start.toString());
                                                                                                          resolve(true);
                                                                                                          }, 1000);
                                                                                                          });
                                                                                                          }
                                                                                                          return true;
                                                                                                          }


                                                                                                          And then you call run it like so:



                                                                                                          looper().then(function(){
                                                                                                          console.log("DONE!")
                                                                                                          });


                                                                                                          Please take some time to get a good understanding of asynchronous programming.






                                                                                                          share|improve this answer













                                                                                                          To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:



                                                                                                          var looper = async function () {
                                                                                                          for (var start = 1; start < 10; start++) {
                                                                                                          await new Promise(function (resolve, reject) {
                                                                                                          setTimeout(function () {
                                                                                                          console.log("iteration: " + start.toString());
                                                                                                          resolve(true);
                                                                                                          }, 1000);
                                                                                                          });
                                                                                                          }
                                                                                                          return true;
                                                                                                          }


                                                                                                          And then you call run it like so:



                                                                                                          looper().then(function(){
                                                                                                          console.log("DONE!")
                                                                                                          });


                                                                                                          Please take some time to get a good understanding of asynchronous programming.







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Feb 23 at 22:35









                                                                                                          Questionare232Questionare232

                                                                                                          101112




                                                                                                          101112























                                                                                                              -1














                                                                                                              Here is a function that I use for looping over an array:



                                                                                                              function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

                                                                                                              if (i < theArray.length && typeof delayAmount == 'number'){

                                                                                                              console.log("i "+i);

                                                                                                              theFunction(theArray[i], i);

                                                                                                              setTimeout(function(){

                                                                                                              loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                                                                                                              }else{

                                                                                                              onComplete(i);
                                                                                                              }
                                                                                                              }


                                                                                                              You use it like this:



                                                                                                              loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                                                                                                              //Do something with item
                                                                                                              }, function(i){
                                                                                                              //Do something once loop has completed
                                                                                                              }





                                                                                                              share|improve this answer




























                                                                                                                -1














                                                                                                                Here is a function that I use for looping over an array:



                                                                                                                function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

                                                                                                                if (i < theArray.length && typeof delayAmount == 'number'){

                                                                                                                console.log("i "+i);

                                                                                                                theFunction(theArray[i], i);

                                                                                                                setTimeout(function(){

                                                                                                                loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                                                                                                                }else{

                                                                                                                onComplete(i);
                                                                                                                }
                                                                                                                }


                                                                                                                You use it like this:



                                                                                                                loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                                                                                                                //Do something with item
                                                                                                                }, function(i){
                                                                                                                //Do something once loop has completed
                                                                                                                }





                                                                                                                share|improve this answer


























                                                                                                                  -1












                                                                                                                  -1








                                                                                                                  -1







                                                                                                                  Here is a function that I use for looping over an array:



                                                                                                                  function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

                                                                                                                  if (i < theArray.length && typeof delayAmount == 'number'){

                                                                                                                  console.log("i "+i);

                                                                                                                  theFunction(theArray[i], i);

                                                                                                                  setTimeout(function(){

                                                                                                                  loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                                                                                                                  }else{

                                                                                                                  onComplete(i);
                                                                                                                  }
                                                                                                                  }


                                                                                                                  You use it like this:



                                                                                                                  loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                                                                                                                  //Do something with item
                                                                                                                  }, function(i){
                                                                                                                  //Do something once loop has completed
                                                                                                                  }





                                                                                                                  share|improve this answer













                                                                                                                  Here is a function that I use for looping over an array:



                                                                                                                  function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

                                                                                                                  if (i < theArray.length && typeof delayAmount == 'number'){

                                                                                                                  console.log("i "+i);

                                                                                                                  theFunction(theArray[i], i);

                                                                                                                  setTimeout(function(){

                                                                                                                  loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                                                                                                                  }else{

                                                                                                                  onComplete(i);
                                                                                                                  }
                                                                                                                  }


                                                                                                                  You use it like this:



                                                                                                                  loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                                                                                                                  //Do something with item
                                                                                                                  }, function(i){
                                                                                                                  //Do something once loop has completed
                                                                                                                  }






                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Jun 2 '15 at 1:38









                                                                                                                  PJeremyMaloufPJeremyMalouf

                                                                                                                  44759




                                                                                                                  44759























                                                                                                                      -1














                                                                                                                      This script works for most things



                                                                                                                      function timer(start) {
                                                                                                                      setTimeout(function () { //The timer
                                                                                                                      alert('hello');
                                                                                                                      }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                                                                                                                      }

                                                                                                                      for(var start = 1; start < 10; start++) {
                                                                                                                      timer(start);
                                                                                                                      }





                                                                                                                      share|improve this answer




























                                                                                                                        -1














                                                                                                                        This script works for most things



                                                                                                                        function timer(start) {
                                                                                                                        setTimeout(function () { //The timer
                                                                                                                        alert('hello');
                                                                                                                        }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                                                                                                                        }

                                                                                                                        for(var start = 1; start < 10; start++) {
                                                                                                                        timer(start);
                                                                                                                        }





                                                                                                                        share|improve this answer


























                                                                                                                          -1












                                                                                                                          -1








                                                                                                                          -1







                                                                                                                          This script works for most things



                                                                                                                          function timer(start) {
                                                                                                                          setTimeout(function () { //The timer
                                                                                                                          alert('hello');
                                                                                                                          }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                                                                                                                          }

                                                                                                                          for(var start = 1; start < 10; start++) {
                                                                                                                          timer(start);
                                                                                                                          }





                                                                                                                          share|improve this answer













                                                                                                                          This script works for most things



                                                                                                                          function timer(start) {
                                                                                                                          setTimeout(function () { //The timer
                                                                                                                          alert('hello');
                                                                                                                          }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                                                                                                                          }

                                                                                                                          for(var start = 1; start < 10; start++) {
                                                                                                                          timer(start);
                                                                                                                          }






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Mar 19 '16 at 2:00









                                                                                                                          Jaketr00Jaketr00

                                                                                                                          672632




                                                                                                                          672632























                                                                                                                              -1

















                                                                                                                              var timer, i = 10;
                                                                                                                              function myLoop () { // create a loop function
                                                                                                                              timer = setTimeout(function () {
                                                                                                                              document.getElementById("demo").innerHTML = i;

                                                                                                                              i--;
                                                                                                                              if (i >= 0) {
                                                                                                                              myLoop();
                                                                                                                              } else {
                                                                                                                              clearTimeout(timer); // clear timeout
                                                                                                                              document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                              }

                                                                                                                              }, 1000);
                                                                                                                              }

                                                                                                                              myLoop();

                                                                                                                              <p id="demo">count</p>








                                                                                                                              share|improve this answer




























                                                                                                                                -1

















                                                                                                                                var timer, i = 10;
                                                                                                                                function myLoop () { // create a loop function
                                                                                                                                timer = setTimeout(function () {
                                                                                                                                document.getElementById("demo").innerHTML = i;

                                                                                                                                i--;
                                                                                                                                if (i >= 0) {
                                                                                                                                myLoop();
                                                                                                                                } else {
                                                                                                                                clearTimeout(timer); // clear timeout
                                                                                                                                document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                                }

                                                                                                                                }, 1000);
                                                                                                                                }

                                                                                                                                myLoop();

                                                                                                                                <p id="demo">count</p>








                                                                                                                                share|improve this answer


























                                                                                                                                  -1












                                                                                                                                  -1








                                                                                                                                  -1










                                                                                                                                  var timer, i = 10;
                                                                                                                                  function myLoop () { // create a loop function
                                                                                                                                  timer = setTimeout(function () {
                                                                                                                                  document.getElementById("demo").innerHTML = i;

                                                                                                                                  i--;
                                                                                                                                  if (i >= 0) {
                                                                                                                                  myLoop();
                                                                                                                                  } else {
                                                                                                                                  clearTimeout(timer); // clear timeout
                                                                                                                                  document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                                  }

                                                                                                                                  }, 1000);
                                                                                                                                  }

                                                                                                                                  myLoop();

                                                                                                                                  <p id="demo">count</p>








                                                                                                                                  share|improve this answer
















                                                                                                                                  var timer, i = 10;
                                                                                                                                  function myLoop () { // create a loop function
                                                                                                                                  timer = setTimeout(function () {
                                                                                                                                  document.getElementById("demo").innerHTML = i;

                                                                                                                                  i--;
                                                                                                                                  if (i >= 0) {
                                                                                                                                  myLoop();
                                                                                                                                  } else {
                                                                                                                                  clearTimeout(timer); // clear timeout
                                                                                                                                  document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                                  }

                                                                                                                                  }, 1000);
                                                                                                                                  }

                                                                                                                                  myLoop();

                                                                                                                                  <p id="demo">count</p>








                                                                                                                                  var timer, i = 10;
                                                                                                                                  function myLoop () { // create a loop function
                                                                                                                                  timer = setTimeout(function () {
                                                                                                                                  document.getElementById("demo").innerHTML = i;

                                                                                                                                  i--;
                                                                                                                                  if (i >= 0) {
                                                                                                                                  myLoop();
                                                                                                                                  } else {
                                                                                                                                  clearTimeout(timer); // clear timeout
                                                                                                                                  document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                                  }

                                                                                                                                  }, 1000);
                                                                                                                                  }

                                                                                                                                  myLoop();

                                                                                                                                  <p id="demo">count</p>





                                                                                                                                  var timer, i = 10;
                                                                                                                                  function myLoop () { // create a loop function
                                                                                                                                  timer = setTimeout(function () {
                                                                                                                                  document.getElementById("demo").innerHTML = i;

                                                                                                                                  i--;
                                                                                                                                  if (i >= 0) {
                                                                                                                                  myLoop();
                                                                                                                                  } else {
                                                                                                                                  clearTimeout(timer); // clear timeout
                                                                                                                                  document.getElementById("demo").innerHTML = "DOARRRR ..";
                                                                                                                                  }

                                                                                                                                  }, 1000);
                                                                                                                                  }

                                                                                                                                  myLoop();

                                                                                                                                  <p id="demo">count</p>






                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Feb 18 '18 at 14:41









                                                                                                                                  anteloveantelove

                                                                                                                                  72557




                                                                                                                                  72557























                                                                                                                                      -1














                                                                                                                                      Try this...



                                                                                                                                      var icount=0;
                                                                                                                                      for (let i in items) {
                                                                                                                                      icount=icount+1000;
                                                                                                                                      new beginCount(items[i],icount);
                                                                                                                                      }

                                                                                                                                      function beginCount(item,icount){
                                                                                                                                      setTimeout(function () {

                                                                                                                                      new actualFunction(item,icount);

                                                                                                                                      }, icount);
                                                                                                                                      }

                                                                                                                                      function actualFunction(item,icount){
                                                                                                                                      //...runs ever 1 second
                                                                                                                                      console.log(icount);
                                                                                                                                      }





                                                                                                                                      share|improve this answer




























                                                                                                                                        -1














                                                                                                                                        Try this...



                                                                                                                                        var icount=0;
                                                                                                                                        for (let i in items) {
                                                                                                                                        icount=icount+1000;
                                                                                                                                        new beginCount(items[i],icount);
                                                                                                                                        }

                                                                                                                                        function beginCount(item,icount){
                                                                                                                                        setTimeout(function () {

                                                                                                                                        new actualFunction(item,icount);

                                                                                                                                        }, icount);
                                                                                                                                        }

                                                                                                                                        function actualFunction(item,icount){
                                                                                                                                        //...runs ever 1 second
                                                                                                                                        console.log(icount);
                                                                                                                                        }





                                                                                                                                        share|improve this answer


























                                                                                                                                          -1












                                                                                                                                          -1








                                                                                                                                          -1







                                                                                                                                          Try this...



                                                                                                                                          var icount=0;
                                                                                                                                          for (let i in items) {
                                                                                                                                          icount=icount+1000;
                                                                                                                                          new beginCount(items[i],icount);
                                                                                                                                          }

                                                                                                                                          function beginCount(item,icount){
                                                                                                                                          setTimeout(function () {

                                                                                                                                          new actualFunction(item,icount);

                                                                                                                                          }, icount);
                                                                                                                                          }

                                                                                                                                          function actualFunction(item,icount){
                                                                                                                                          //...runs ever 1 second
                                                                                                                                          console.log(icount);
                                                                                                                                          }





                                                                                                                                          share|improve this answer













                                                                                                                                          Try this...



                                                                                                                                          var icount=0;
                                                                                                                                          for (let i in items) {
                                                                                                                                          icount=icount+1000;
                                                                                                                                          new beginCount(items[i],icount);
                                                                                                                                          }

                                                                                                                                          function beginCount(item,icount){
                                                                                                                                          setTimeout(function () {

                                                                                                                                          new actualFunction(item,icount);

                                                                                                                                          }, icount);
                                                                                                                                          }

                                                                                                                                          function actualFunction(item,icount){
                                                                                                                                          //...runs ever 1 second
                                                                                                                                          console.log(icount);
                                                                                                                                          }






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered May 9 '18 at 9:45









                                                                                                                                          PHILL BOOTHPHILL BOOTH

                                                                                                                                          636




                                                                                                                                          636























                                                                                                                                              -2














                                                                                                                                              Try this



                                                                                                                                              //the code will execute in 1 3 5 7 9 seconds later
                                                                                                                                              function exec(){
                                                                                                                                              for(var i=0;i<5;i++){
                                                                                                                                              setTimeout(function(){
                                                                                                                                              console.log(new Date()); //It's you code
                                                                                                                                              },(i+i+1)*1000);
                                                                                                                                              }
                                                                                                                                              }





                                                                                                                                              share|improve this answer






























                                                                                                                                                -2














                                                                                                                                                Try this



                                                                                                                                                //the code will execute in 1 3 5 7 9 seconds later
                                                                                                                                                function exec(){
                                                                                                                                                for(var i=0;i<5;i++){
                                                                                                                                                setTimeout(function(){
                                                                                                                                                console.log(new Date()); //It's you code
                                                                                                                                                },(i+i+1)*1000);
                                                                                                                                                }
                                                                                                                                                }





                                                                                                                                                share|improve this answer




























                                                                                                                                                  -2












                                                                                                                                                  -2








                                                                                                                                                  -2







                                                                                                                                                  Try this



                                                                                                                                                  //the code will execute in 1 3 5 7 9 seconds later
                                                                                                                                                  function exec(){
                                                                                                                                                  for(var i=0;i<5;i++){
                                                                                                                                                  setTimeout(function(){
                                                                                                                                                  console.log(new Date()); //It's you code
                                                                                                                                                  },(i+i+1)*1000);
                                                                                                                                                  }
                                                                                                                                                  }





                                                                                                                                                  share|improve this answer















                                                                                                                                                  Try this



                                                                                                                                                  //the code will execute in 1 3 5 7 9 seconds later
                                                                                                                                                  function exec(){
                                                                                                                                                  for(var i=0;i<5;i++){
                                                                                                                                                  setTimeout(function(){
                                                                                                                                                  console.log(new Date()); //It's you code
                                                                                                                                                  },(i+i+1)*1000);
                                                                                                                                                  }
                                                                                                                                                  }






                                                                                                                                                  share|improve this answer














                                                                                                                                                  share|improve this answer



                                                                                                                                                  share|improve this answer








                                                                                                                                                  edited Nov 4 '15 at 9:36









                                                                                                                                                  MarmiK

                                                                                                                                                  4,55342841




                                                                                                                                                  4,55342841










                                                                                                                                                  answered Nov 3 '15 at 11:58









                                                                                                                                                  Steve JiangSteve Jiang

                                                                                                                                                  347313




                                                                                                                                                  347313






























                                                                                                                                                      draft saved

                                                                                                                                                      draft discarded




















































                                                                                                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                      But avoid



                                                                                                                                                      • Asking for help, clarification, or responding to other answers.

                                                                                                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                      To learn more, see our tips on writing great answers.




                                                                                                                                                      draft saved


                                                                                                                                                      draft discarded














                                                                                                                                                      StackExchange.ready(
                                                                                                                                                      function () {
                                                                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3583724%2fhow-do-i-add-a-delay-in-a-javascript-loop%23new-answer', 'question_page');
                                                                                                                                                      }
                                                                                                                                                      );

                                                                                                                                                      Post as a guest















                                                                                                                                                      Required, but never shown





















































                                                                                                                                                      Required, but never shown














                                                                                                                                                      Required, but never shown












                                                                                                                                                      Required, but never shown







                                                                                                                                                      Required, but never shown

































                                                                                                                                                      Required, but never shown














                                                                                                                                                      Required, but never shown












                                                                                                                                                      Required, but never shown







                                                                                                                                                      Required, but never shown







                                                                                                                                                      Popular posts from this blog

                                                                                                                                                      Florida Star v. B. J. F.

                                                                                                                                                      Danny Elfman

                                                                                                                                                      Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues