It looks like a timing bug in setTimeout. It isn't. It's var's scope rules doing exactly what they're designed to do — and the fix is one keyword, once you know why.

Adapted from the JavaScript Essentials Companion Guide.

You write a loop that should print 0, 1, and 2, one second apart. Instead you get three 3s.

for (var i = 0; i < 3; i++) {

setTimeout(() => console.log(i), 1000);