4

For example, there is for loop that I want to sleep for some seconds.

$.each(para.res, function (index, item) {
    Sleep(100);
});

I know I can use setTimeout or setInterval but both of them are asychronous, the loop will continue, just the function in the setTimeout will run in a few seconds if I do it this way.

$.each(para.res, function (index, item) {
    setTimeOut(function(){do something},1000); 
});
0x499602D2
  • 87,005
  • 36
  • 149
  • 233
john
  • 297
  • 2
  • 9
  • if you apply sleep in javascript then your javascript will hang and user would not be happy – Ankur Sep 01 '12 at 19:15
  • possible duplicate of [What do I do if I want a JavaScript version of sleep()?](http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep) – João Silva Sep 01 '12 at 19:15
  • yes, i know i just want to do some animation, and i know the delay, but implementation of delay make story difficult. – john Sep 01 '12 at 19:17
  • Almost every time I've been tempted to do so I fixed it using a callback function. What problem are you trying to fix? – Álvaro González Sep 01 '12 at 19:17
  • could you show me what the callback means, just a simple exmaple – john Sep 01 '12 at 19:23
  • @john Rather than giving a function X seconds to finish, you instruct it to warn you when it has finished. – Álvaro González Sep 01 '12 at 19:28

2 Answers2

2

You can define a function.

var i = 0;    
function recursive() {
  setTimeout(function(){
     var item = para.res[i];
     // do something
     i++;        
     if (i < para.res.length) recursive()
  }, 100)
}
undefined
  • 136,817
  • 15
  • 158
  • 186
1

No, there is no built in method for that. You could use a busy loop, but that will freeze the browser in the mean time, and you can't do it for too long because then the browser will stop the script.

If you want the different pieces of code spread out over time, just set different times for setTimeout:

$.each(para.res, function (index, item) {
  setTimeOut(function(){do something},1000 * index); 
});

This will start the code for the first item after one second, the code for the second item after two seconds, and so on.

Or use setInterval:

var index = 0, timer = setInterval(function(){
  if (index < para.res.length) {
    var item = para.res[index];
    // do something
    index++;
  } else {
    clearInterval(timer);
  }
}, 1000);
Guffa
  • 640,220
  • 96
  • 678
  • 956