Complete the code to schedule a function to run repeatedly using setInterval.
setInterval(() => {
console.log('Hello every second');
}, [1]);The setInterval function takes the delay in milliseconds as the second argument. To run every second, use 1000 ms.
Complete the code to create a recursive setTimeout that logs 'Tick' every 2 seconds.
function tick() {
console.log('Tick');
setTimeout(tick, [1]);
}
tick();The recursive setTimeout calls itself after the delay. To run every 2 seconds, use 2000 ms.
Fix the error in the recursive setTimeout code to avoid multiple overlapping calls.
function repeat() {
console.log('Running');
[1](() => {
repeat();
}, 1000);
}
repeat();Using setTimeout recursively schedules the next call after the current one finishes, avoiding overlaps.
Fill both blanks to create a recursive setTimeout that stops after 5 runs.
let count = 0; function run() { if (count [1] 5) { console.log('Run number', count); count++; setTimeout(run, [2]); } } run();
The condition count < 5 stops after 5 runs. The delay 1000 ms makes it run every second.
Fill all three blanks to create a recursive setTimeout that counts down from 3 and then stops.
let num = 3; function countdown() { if (num [1] 0) { console.log(num); num [2] 1; setTimeout(countdown, [3]); } else { console.log('Done!'); } } countdown();
The countdown stops when num > 0 is false. The -= 1 decreases the number by one each time. The delay 1000 ms makes it run every second.