0
0
Node.jsframework~10 mins

Recursive setTimeout vs setInterval in Node.js - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to schedule a function to run repeatedly using setInterval.

Node.js
setInterval(() => {
  console.log('Hello every second');
}, [1]);
Drag options to blanks, or click blank then click option'
A1000
B5000
C10
D100
Attempts:
3 left
💡 Hint
Common Mistakes
Using 100 instead of 1000 causes the function to run every 0.1 seconds.
Using 5000 runs the function every 5 seconds, which is slower than intended.
2fill in blank
medium

Complete the code to create a recursive setTimeout that logs 'Tick' every 2 seconds.

Node.js
function tick() {
  console.log('Tick');
  setTimeout(tick, [1]);
}
tick();
Drag options to blanks, or click blank then click option'
A500
B1000
C2000
D3000
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1000 causes the function to run every 1 second instead of 2.
Using 3000 causes the function to run every 3 seconds, which is slower.
3fill in blank
hard

Fix the error in the recursive setTimeout code to avoid multiple overlapping calls.

Node.js
function repeat() {
  console.log('Running');
  [1](() => {
    repeat();
  }, 1000);
}
repeat();
Drag options to blanks, or click blank then click option'
AsetInterval
BsetTimeout
CclearTimeout
DclearInterval
Attempts:
3 left
💡 Hint
Common Mistakes
Using setInterval causes the function to run repeatedly without waiting for the previous call to finish.
Using clearTimeout or clearInterval here is incorrect because they cancel timers.
4fill in blank
hard

Fill both blanks to create a recursive setTimeout that stops after 5 runs.

Node.js
let count = 0;
function run() {
  if (count [1] 5) {
    console.log('Run number', count);
    count++;
    setTimeout(run, [2]);
  }
}
run();
Drag options to blanks, or click blank then click option'
A<
B<=
C1000
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= 5 causes the function to run 6 times instead of 5.
Using 500 ms delay runs the function twice as fast as intended.
5fill in blank
hard

Fill all three blanks to create a recursive setTimeout that counts down from 3 and then stops.

Node.js
let num = 3;
function countdown() {
  if (num [1] 0) {
    console.log(num);
    num [2] 1;
    setTimeout(countdown, [3]);
  } else {
    console.log('Done!');
  }
}
countdown();
Drag options to blanks, or click blank then click option'
A>
B-=
C1000
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < 0 causes the countdown to never stop.
Using += 1 increases num and causes an infinite loop.
Using delay other than 1000 changes the timing.