1

I need to have a delay in my JavaScript code, but I'm having problems if I create a timeout function in my code. However, if I take out the timeout code it works perfectly fine. I searched through the other post in here about timeout/delay but my case is a little bit different I think.

var myArray = new Array('Book One', 'Book Two', 'Book Three', 'Book Four');

x = myArray.length - 1;

(function myLoop(x) {

    page = 3;

    (function myLoop2(page) {
        //setTimeout(function () {   

        var name = myArray[x];

        alert(name + ' Page: ' + page);

        if (--page) myLoop2(page);
        //}, 1000 )
    })(page);

    if (x != 0) myLoop(--x);
})(x);

If I remove the comment in the code, it will give me a different output.

Andreas
  • 5,393
  • 9
  • 44
  • 53
Alex Strauss
  • 121
  • 3
  • 7

2 Answers2

0

Unfortunately there is no sleep or wait function in JavaScript. Timeout will not pause program execution. Instead it will schedule the function to be executed at some later point, and continue as if nothing has happened at this moment.

So, without the timeout, the code runs as a normal nested loop.

With timeout, the inner loop becomes 'schedule once, and when triggered schedule next'. So the outer loop will schedule all the first page of each book. After a second the first pages are triggered, which will schedule the second pages. After another sec the second pages are triggered, and so on.

Sheepy
  • 17,324
  • 4
  • 45
  • 69
  • thanks for the response, I'm not that quite familiar in the javascript, so if it is there no sleep function just like in PHP, how can i delay the function inside my loop? is there any other way to do this? – Alex Strauss Jan 30 '13 at 07:19
  • Dontt think so. some good explenations about javascript not sleeping found in: http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep – roel Jan 30 '13 at 08:33
0

Yea there is no sleep/wait function in Javascript. But you can do most of required functonalities using SetTimeout function.

I think the following code will give you desired result. Check it

var myArray = new Array('Book One', 'Book Two', 'Book Three', 'Book Four');

x = myArray.length - 1;

   (function myLoop(x2) {

    page = 3;

    (function myLoop2(page1, x1) {


       setTimeout(function () {  var name = myArray[x1];

    alert(name + ' Page: ' + page1);

    if (--page1)  myLoop2(page1, x1);}, 1000 )

    })(page,x2); 

    if (x2 != 0)  setTimeout(function () {myLoop(--x2);}, 4000 )
})(x);

We have to use setTimeout function according to the circumstances. setTimeout will not block the code flow.

use of global varibles inside Timed function will result in using variable at executed time instance. Not the value which was when the function was timed in setTimeout function.

999k
  • 6,257
  • 2
  • 29
  • 32