user2631296
user2631296

Reputation: 903

update graph with new data

I have a list of files that I want to plot in order (line graph), creating an animation as d3 transitions between them.

I have an update function that takes as input a file name, and transitions the current line graph to the new line graph. This is working fine.

However, I now want to transition in order between five different files.

Here is the code I am using:

var file_list = ["time1.csv", "time2.csv", "time3.csv", "time4.csv", "time5.csv"];

var num_files = file_list.length;

for (i = 0; i < num_files; ++i) {
    setTimeout(setDelay(i), 1000);
}

function setDelay(i) {
  setTimeout(function(){
    update(file_list[i]);
  }, 1000);
}

This does transition my line graph, but it transitions from the first (time1.csv) immediately to the last (time5.csv), skipping everything in the middle.

How can I figure out what is going wrong?

If I console.log(file_list[i]) in the loop, it is looping through and printing time1.csv ... time5.csv.

Thanks!

Upvotes: 0

Views: 79

Answers (1)

allisonvoll
allisonvoll

Reputation: 36

The setDelay is called on every iteration, to evaluate it on timeout you must pass the function object as callback setTimeout(function() { setDelay(i); }, 1000)

But your logic is wrong, why two setTimeout per iteration? All of them is calling immediatly after each iteration, you must chain the setDelay calls or multiply the delay by iteration index.

var file_list = ["time1.csv", "time2.csv", "time3.csv", "time4.csv", "time5.csv"];

function setDelay() {
    var file = file_list.shift();
    if (file) {
        update(file);
        setTimeout(setDelay, 1000);
    }
}

setDelay();

Upvotes: 2

Related Questions