Skip to content
Swizec Teller - a geek with a hatswizec.com

Kids, always remember to clear your intervals

Making fake demo graphs is always fun. Here you are, making a graph without data, generating random datapoints, trying to make it as realistic as possible.

Two days ago I was failing at the same.

It sounds simple, right? To produce a random graph, you generate random data. Something like this:

var data = _.range(250).map(function () {
return Math.round(Math.random() * 100);
});

And your graph will look like this:

Completely random graph
Completely random graph

Well, that doesn't look realistic at all. Crazy spikes, deep valleys ... if a real-world system behaved like this you would be very concerned for its wellbeing. This won't do for a demo.

And besides, you wanted a live graph anyway.

So you move data generation into the backend and hook it up with socket.io. Then you make a function that generates one datapoint every 250ms.

Data generation looks like this:

io.on("connection", function (socket) {
setInterval(function () {
socket.emit("cpu", update());
}, 250);
function update() {
return Math.round(Math.random() * 100);
}
});

Your graph now looks like this:

Moving random graph

Yay! It moves!

But still too random to look realistic. A CPU that behaves like that is in serious trouble!

What if instead of producing random values, we produced random changes to existing values? That could work. Remember the previous state, make a tiny random change.

Data generation now looks like this:

io.on('connection', function (socket) {
var previous = 0;
setInterval(function () {
previous = update(previous);
socket.emit('cpu', previous);
}, 250);
function (previous) {
previous += Math.random()*10-5;
if (previous > 100) previous = 100;
if (previous < 0) previous = 0;
return Math.round(previous);
}
});

And the graph looks like this:

Fixed random graph, 1

Or like this:

Fixed random graph, 2

Or even like this:

Fixed random graph, 3

Wait ... what? That's even worse than before! How is this possible, the value changes on each step are tiny?

And I wrecked my brain and wrecked my brain and then wrecked my brain some more. Refreshed the page many times. Rewrote the data generating function many times. Nothing I tried worked. The graph looked more sporadic than ever.

Can you spot the error?

The clue lies in those graphs moving faster and faster with each refresh. Something fucky is going on - the uncleared setInterval.

You see, that backend node.js process is persistent. The 250 millisecond interval doesn't just go away when you refresh the page. Oh no, it's still there, waiting for you, stalking its prey, hunting.

And because socket.io does evertyhing in its power to be more reliable than not, it will reconnect old sockets because hey, you probably just have spotty wi-fi. But we also started a new setInterval on every connection event.

Yeah.

That's not a single random function acting funny, that's a whole bunch of them!

If we fix the backend code to look like this:

io.on('connection', function (socket) {
var previous = 0;
var interval = setInterval(function () {
previous = update(previous);
socket.emit('cpu', previous);
}, 250);
function (previous) {
previous += Math.random()*10-5;
if (previous > 100) previous = 100;
if (previous < 0) previous = 0;
return Math.round(previous);
}
socket.on('disconnect', function () {
clearInterval(interval);
});
});

The graph looks like this:

Moving graph, good

And all is right in the world.

You're happy, your boss is happy, your graph looks like it could be real but isn't. Acting.

Did you enjoy this article?

Published on November 5th, 2014 in JavaScript, Node.js, socket.io, Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️