11.1. Print 1 to 10, one per second
Topics
This question is in
11. Timers"Print the numbers 1 to 10, one per second" sounds like a warm-up, but it tests three things at once: how timers are scheduled, how to stop a repeating timer, and what a closure captures inside a loop. The classic trap is a for loop over a var that schedules ten timeouts and prints 11 ten times, because every callback reads the same variable after the loop has finished.
Write three functions in count.js. Each one prints 1 to 10 by calling print(n): 1 after one second, 2 after two seconds, and so on up to 10 after ten seconds. They differ in the tools they may use.
Signature
function printWithTimeouts(print) // setTimeout only
function printWithInterval(print) // one setInterval that stops itself
function printWithoutLet(print) // setTimeout and var: no let or constprint: a function; call it with exactly one argument, the number.- Each function returns
undefinedstraight away; the printing happens later.
Requirements
- Nothing is printed during the call itself.
nis printed exactlyn × 1000ms after the call:1at 1000 ms (not at 999),10at 10000 ms.- Exactly the numbers 1 to 10 are printed, in order, each once, and nothing after
10, however long you wait. printreceives exactly one argument, the number.- When it is done, no timer is left waiting: a repeating timer must be cleared.
printWithTimeoutsusessetTimeoutand neversetInterval.printWithIntervalcallssetIntervalexactly once and neversetTimeout.printWithoutLetcontains neitherletnorconst, not even in a comment (the tests read the function's source).- Calling a function twice starts two independent runs that do not cut each other short.
Examples
printWithTimeouts(console.log);
// 1 s: 1
// 2 s: 2
// …
// 10 s: 10, and then nothing more// The trap printWithoutLet must avoid:
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), i * 1000);
}
// 1 s: 4, 2 s: 4, 3 s: 4: every callback reads the same i, after the loop endedEnvironment
- Plain JavaScript in a browser page; the tests call the three global functions from
count.js. - The tests run on a virtual clock that replaces
setTimeout,setIntervaland their clear functions, so use those (no busy loops, norequestAnimationFrame). - In
printWithoutLet, function parameters are allowed:letandconstare the only words that are not.
Hints
- In the trap above, how many variables named
iare there, and what value does it hold when the first callback runs? - Without
let, what else creates a new scope, or a new copy of a value, for each turn of the loop? - How does an interval callback know it has run for the tenth time, and where does it find the id to clear?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it