Skip to content

QuizNot attempted

Spot the bug: clearTimeout on a fresh local

What does clearTimeout(timer) cancel?
const loadMoreData = () => {
let timer = 0;
clearTimeout(timer);
if (currentPage < totalItems && !isFetching) {
setIsFetching(true);
timer = setTimeout(() => {
/* append the next page */
}, 1000);
}
};
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Nothing: timer is a new local set to 0 on every call, so no earlier timeout is ever cancelled
  • Each call gets its own timer
  • the previous call's id is gone.
  • To cancel a timeout later, keep the id somewhere that outlives the call (timerRef.current) and also clear it in an effect cleanup so it can't fire after unmount.
  • Not the previous call's timeout: that id was in a different call's local variable.
  • Not every pending timeout: clearTimeout clears only the id you pass.
  • Not it throws: unknown or invalid ids are silently ignored.