setTimeout and clearTimeout. What will be printed to the console?const timer = setTimeout(() => {
console.log('Hello after 1 second');
}, 1000);
clearTimeout(timer);
console.log('Timer cleared');clearTimeout does to a scheduled timer.The setTimeout schedules a function to run after 1 second. However, clearTimeout cancels this scheduled function before it runs. So only the immediate console.log('Timer cleared') runs.
count after this code runs?setTimeout. What will be the final value of count after 1500 milliseconds?let count = 0; const timer = setTimeout(() => { count += 1; }, 1000); setTimeout(() => { clearTimeout(timer); }, 500); setTimeout(() => { console.log(count); }, 1500);
The first timer is set to increment count after 1000ms. But it is cleared after 500ms, so it never runs. Therefore, count remains 0.
setInterval. Which code snippet correctly cancels it?const intervalId = setInterval(() => {
console.log('Tick');
}, 1000);
// Which line correctly stops the interval?setTimeout and setInterval cancellation functions.setInterval timers must be cancelled with clearInterval. Using clearTimeout will not stop the interval.
const timer = setTimeout(function repeat() {
console.log('Hello');
setTimeout(repeat, 1000);
}, 1000);
setTimeout(() => {
clearTimeout(timer);
console.log('Stopped');
}, 3000);The code creates a new timer inside the repeat function each time it runs. The clearTimeout(timer) only cancels the original timer, but the new timers keep running indefinitely.
let count = 0; const timer = setTimeout(() => { console.log('Timeout 1:', count); }, 1000); const timer2 = setTimeout(() => { console.log('Timeout 2:', count); }, 1500); count = 5; clearTimeout(timer); setTimeout(() => { console.log('Final count:', count); }, 2000);
count changes.The first timer is cleared before it runs, so it never prints. The second timer runs after 1.5 seconds and prints the current value of count, which is 5. The final timer prints the count after 2 seconds, also 5.