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:



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
  • B
  • C
  • D
Reveal correct answer

Correct answer: B

Explanation

Topic: setInterval() clearInterval()


Try it yourself:


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.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need