Javascript Developer JSE 40 01 · Free Practice Question Medium
Question 6
Q233 - Functions
In the following code fragment, where we use setInterval
one line is missing:
- let counter = 2;
- let interval = setInterval(() => {
- console.log(counter);
- // Missing line
- }, 1000);
What should the missing line look like if the execution of this code
results in the console displaying the values 2, 1 and 0 in sequence?
-
A
- if (counter-- >= 0) clearInterval(interval);
-
B
- if (counter-- <= 0) clearInterval(interval);
-
C
- clearInterval(interval);
-
D
- while (counter-- >= 0) clearInterval(interval);
Reveal correct answer
Correct answer: B
Explanation
Topic: setInterval() clearInterval()
Try it yourself:
- let counter1 = 2;
- let interval1 = setInterval(() => {
- console.log(counter1); // 2 1 0
- if (counter1-- <= 0) clearInterval(interval1);
- }, 1000);
- let counter2 = 2;
- let interval2 = setInterval(() => {
- // console.log(counter2); // 2
- clearInterval(interval2);
- }, 1000);
- let counter3 = 2;
- let interval3 = setInterval(() => {
- // console.log(counter3); // 2
- if (counter3-- >= 0) clearInterval(interval3);
- }, 1000);
- let counter4 = 2;
- let interval4 = setInterval(() => {
- // console.log(counter4); // 2
- while (counter4-- >= 0) clearInterval(interval4);
- }, 1000);
Explanation:
You only want to clear the timer when the counter is less than or equal to 0
Therefore you need: if (counter-- <= 0)
All other three would only display 2 and then clear the timer.
The setInterval() method calls a function
at specified intervals (in milliseconds).
https://www.w3schools.com/jsref/met_win_setinterval.asp
The clearInterval() method clears a timer
set with the setInterval() method.
https://www.w3schools.com/jsref/met_win_clearinterval.asp
Q233 (Please refer to this number, if you want to write me about this question.)
A. This choice incorrectly checks if the counter variable is greater than or equal to 0, which is not the condition needed to display the values 2, 1, and 0 in sequence. It will clear the interval prematurely.
B. The missing line should decrement the counter variable and check if it is less than or equal to 0. If the condition is met, it clears the interval using clearInterval, stopping the execution of the setInterval function and preventing further console outputs.
C. This choice only clears the interval immediately without checking the value of the counter variable. It does not ensure that the console displays the values 2, 1, and 0 in sequence as required.
D. Using a while loop in this context is incorrect as it will continuously decrement the counter variable and attempt to clear the interval multiple times. This will not achieve the desired result of displaying the values 2, 1, and 0 in sequence.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
