Contents

How to Loop with Intervals in D3.js?

Contents

In this post we will see how to add interactivity to our visualization.

An easy way for us to replicate an update in D3 is to use an interval.

1
2
3
d3.interval( () => {
	//your code
}, 1000) //runs every second

We basically want to run some code repeatedly every few seconds, changing the data that we are looking. D3 provides its own interval function for doing this, which takes two arguments. A function to run continuously and a delay in milliseconds.

The code inside the callback above will run every 1000 milliseconds (or every second) tarting as soon as the browser sees.

The way that we are using this interval is similar to the setInterval function in JavaScript.

1
2
3
4
5
6
const myloop = setInterval( () => {
	//your code
}, 1000) //runs every second

//stop the loop
clearInterval(myInterval)

The difference is that the setInterval function allows us pause our loop by calling the clearInterval function.

To start off, we just write the D3 interval function at the end of the data loading function.

1
2
3
4
5
d3.interval( () => {

	console.log("Hello World!");
	
}, 1000) //runs every second

This snippet above will display “Hello World!” every second in the console of the web browser.

You can run any function in the d3.interval function and that is what we will doing in next posts when we would like to make our charts dynamic.

That’s it for this post. I hope you enjoyed it. Do not hesitate to ask your questions in DM.

See you!