Blog>
Snippets

Cleaning Up Timers and Intervals

Provide an example of creating and clearing timers or intervals (such as setTimeout or setInterval) to prevent memory leaks by ensuring that all intervals and timeouts are cleared when they’re no longer necessary.
// Creating a timer using setTimeout
var timer = setTimeout(function() {
  console.log('This function runs after 2 seconds');
}, 2000);

// Clearing the timer
// Use this if you need to cancel the timeout before it executes
setTimeout(function() {
  clearTimeout(timer);
  console.log('Timer cleared before it could execute.');
}, 1000);
This code sets up a timer to execute a function after 2 seconds. Before the timer triggers, it is cleared using clearTimeout, so the timer's function will never execute.
// Creating an interval using setInterval
var interval = setInterval(function() {
  console.log('This function runs every 3 seconds');
}, 3000);

// Assume we want to clear the interval after 10 seconds
setTimeout(function() {
  clearInterval(interval);
  console.log('Interval cleared after 10 seconds.');
}, 10000);
This code creates an interval that logs a message every 3 seconds. An additional timer is set to clear this interval after 10 seconds to prevent it from running indefinitely.