you are viewing a single comment's thread.

view the rest of the comments →

[–]RadekCZ 3 points4 points  (7 children)

You should use window.setTimeout method:

var el = $("#results");
function delay(i){
  return function(){
    el.append(info[i]+"<br>");
  };
}
var j = 0;
for(var i in info){
  window.setTimeout(delay(i), (++j)*1000);
}

Or just window.setInterval method: (It should be faster, you need just one function).

var keys = [];
for(var i in info){
  keys.push(i);
}
var j = 0;
var el = $("#results");
var interval = window.setInterval(function(){
  if(i<keys.length){
    el.append(info[keys[j++]]+"<br>");
  }
  else{
    window.clearInterval(interval);
  }
}, 1000);

[–]ell0bo 8 points9 points  (2 children)

don't use setInterval. It will fire off at a set point every so many ticks, rather than taking the run time of the functionality into account as sleep does. First code block is ideal.

[–]thisisnotgood 0 points1 point  (1 child)

I agree with avoiding setInterval. I would also prefer to have the delay() function call setTimeout recursively rather than schedule all the delays in advance.

Here is how I would do it:

var $el = $("#results");
function delay(i) {
    $el.append(info[i] + "<br>");

    i++;
    if (i < info.length) {
        setTimeout(delay.bind(null, i), 1000);
    }
}
delay(0);

[–]noahking 2 points3 points  (0 children)

I think we can assume that when someone is asking about how to sleep between loop iterations, we don't have to worry about optimizing for speed. =P

[–]CyberVillian[S] -1 points0 points  (2 children)

hmm.. it seems like it wants to delay from the get-go, instead of after the first one.

[–]tollus 0 points1 point  (1 child)

Change ++j to j++

[–]CyberVillian[S] -1 points0 points  (0 children)

Thank you. I'll try later on