Timer start in JavaScript

Although the setTimeout function is not designed to create timers, you can still make them with it if you use recursion:

let i = 0; function timer() { setTimeout(function() { console.log(++i); timer(); // let's call ourselves }, 1000); } timer();

You can stop such a timer simply without letting the recursion happen:

let i = 0; function timer() { setTimeout(function() { console.log(++i); if (i < 10) { // runs only if counter is less than 10 timer(); } }, 1000); } timer();

Print the number 0 to the console. After one second - print the number 1, after two seconds - print the number 2, after 3 seconds - print the number 3. And so on ad infinitum.

enru