An "interview question" about js timer

clipboard.png

I hope to explain it in detail

Why can

clearTimeout (tc) clear the last setTimeout?

May.23,2022

because js has no block-level scope, only global scope and function scope. So, the code actually goes like this:

  

the next four timers are executed after the for loop has been executed four times; but because the tc is defined four times in the for loop, each definition will reassign the previous tc, which is equivalent to defining tc four times, and only the last time is valid, so only the last tc is cleared

.
Menu