-1

I need to pause a while loop for a certain amount of time based on a condition

var i = 2

while (i) {
    if (i == 2) {
        //pause loop for 5 seconds
        //execute function1();
    } else {
        //pause loop for 4 seconds
        //execute function2();
    }
}

How could I achieve this. Thank you

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
Barry Hamilton
  • 943
  • 3
  • 15
  • 35

2 Answers2

1

You could do something like this:

var i = 2,
    method1 = function() {
        //do your thing
        start();
    },
    method2 = function() {
        //do your thing
        start();
    },
    start = function() {
        if( i && i == 2 ) {
            setTimeout(method1,5000);
        }
        else if( i ) {
            setTimeout(method2,4000);
        }
    }
;

You need to call the start() method at the end of the delayed methods. This way, you avoid a huge number of setTimeout(method1,5000) being called before the 5 seconds is even up.

Kevin Nelson
  • 7,613
  • 4
  • 31
  • 42
  • You beat me to it :) Here's a fiddle for what I did though, basically the same thing. http://jsfiddle.net/ubq2Lqzv/ – Wet Noodles Nov 14 '14 at 16:01
-1

use the setTimeout() to achieve what you want.

http://www.w3schools.com/jsref/met_win_settimeout.asp

Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10
  • when I use timeout it pauses the execution but continues the loop all that happens istheirs 000's of functions executing killing the browser. – Barry Hamilton Nov 14 '14 at 15:53