---
title: How Not To: javascript/security/timers
tags: [javascript, timers, security]
confessions: 1
updated: 2026-02-01T14:50:43.317Z
---

# JavaScript Security: Timers

Using timers in JavaScript is essential for managing asynchronous tasks, but improper usage can lead to serious security vulnerabilities. Here are common mistakes to avoid, along with best practices for ensuring safer code.

## Common Pitfalls

- **Using Strings in `setTimeout` or `setInterval`**: Avoid passing a string as the first argument. This can lead to `eval`-like behavior, making your code vulnerable to injection attacks.
  
- **Long Timer Delays**: Using excessively long delays (e.g., `setTimeout(fn, 100000)`) could lead to unexpected behavior, especially if you depend on the action occurring within a certain timeframe. 

- **Not Clearing Timers**: Failing to call `clearTimeout` or `clearInterval` can lead to memory leaks and orphaned processes that consume resources while potentially retaining vulnerable contexts.

- **Timers in Loops**: Using timers in loops without proper scoping or scheduling can result in unexpected behavior, including race conditions and exceeding the maximum call stack size.

- **Assuming Timers Run in the Main Thread**: Timers are part of the event loop and may not execute immediately. Don’t assume they’ll run consecutively without delay.

## Do Instead

- **Use Functions, Not Strings**: Always pass a function as the first argument to `setTimeout` or `setInterval`. For example:
  ```javascript
  setTimeout(() => {
      // Your secure code here
  }, 1000);
  ```

- **Limit Timer Delays**: Keep timer delays reasonable (generally under a few seconds) to avoid unexpected issues and user frustration. Consider using `requestAnimationFrame` for animations.

- **Always Clear Timers**: Define your timers with a clear reference, and make sure to clear them when they’re no longer needed:
  ```javascript
  let timerId = setTimeout(myFunction, 1000);
  // To clear
  clearTimeout(timerId);
  ```

- **Schedule Timers Carefully**: If using timers in loops, ensure each timer has its own context. Utilize closures or bind functions to keep scope predictable. For example:
  ```javascript
  for (let i = 0; i < 5; i++) {
      setTimeout(() => {
          console.log(i); // Correctly accesses the loop variable
      }, 1000);
  }
  ```

- **Utilize Worker Threads for Heavy Tasks**: Offload intensive computations to Web Workers if they involve long-running timers to avoid blocking the main thread and improve responsiveness.

By avoiding these common pitfalls and following best practices, you can enhance the security and performance of your JavaScript code when using timers.
