Dionysus Dionysus - 2 months ago 5
Javascript Question

$.each display data then pause for 3 seconds

I'm iterating a JSON file using

.each()
. I want my page to show data for say 3 seconds, pause for 3 seconds then move on to the next one and repeat. I have this code:

$.getJSON(url,function(json1){
$.each(json1.data,function(numb){
setTimeout(function() {
alert(json1.data[numb]["title"]);
},3000);
});
});


I thought this would do it but this only waits for 3 seconds and then displays each bit of data in succession, and I need them to be 3 seconds apart.

How do I get that? Thanks!

Answer

Times by the index:-

$.getJSON(url, function(json1) {
  $.each(json1.data, function(numb) {
    setTimeout(function() {
      alert(json1.data[numb]["title"]);
    }, 3000 * num);
  });
});

This will make the 1st 0 seconds, 2nd 3 seconds, 3rd 6 seconds, etc.

or it you want the 1st to wait also, use:

3000 * (num+1)
Comments