1

I'm loading a JSON file and doing a $.each on the results. However, I want a delay between processing each item in the JSON data. I have the following code, but it waits 1000 ms then outputs all the item.time values at once.

   $.getJSON("data/data.json", function() {
       }).done(function(d) {
       console.log("Got JSON");
       $d.each(function(i, item){
           setTimeout( function(){
               series.append(item.time, item.value);
               console.log(item.time)}, 1000)
       });
   });
  • check out http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop – Neil S Sep 29 '15 at 17:39

2 Answers2

2

Try the following - made a few changes to the some part of the structure.

Unfortunately, didnt get to test it due to not having any data set.

$.getJSON( "data/data.json", function() {
    console.log( "success" );
}).done(function(data) {
    $.each( data, function( i, item ) {
        setTimeout(function () {
            series.append(item.time, item.value);
            console.log(item.time)
        }, i * 1000);
    });
})

Added the index element to increase as each element is going through as the delay needs to grow so its chronological order.

Example:

Say if you have 10 data sets, now using the $.each function, you can loop through those and append the correct element to the DOM (easy...).

Now if you want to add a pause between each element so the first one loads, then after 1 second, the next one loads, you cant use the static 1000ms delay. You need to increase the number as it goes down the data set. Otherwise, all it will do is wait 1000ms and then show everything at the same time.

To space them out, and within the $.each function, you get the index as a callback that can be used. So simple implementation would be to just times (*) the timeout so it starts with 1000ms and then the next one would be 2000ms (but just a one second delay from the first element).

jagmitg
  • 4,236
  • 7
  • 25
  • 59
0

Change your call to setTimeout:

       setTimeout( function(){
           series.append(item.time, item.value);
           console.log(item.time)}, i * 1000)

All the setTimeout are called at the same time (in the loop) and they all trigger execution to 1000 from now. To space them, just multiply the delay by index-> 1000 * i and you'll get the desired result.

Meir
  • 14,081
  • 4
  • 39
  • 47