> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/grafana/k6/llms.txt
> Use this file to discover all available pages before exploring further.

# k6/timers

> Timer functions for scheduling asynchronous operations in k6 tests

# k6/timers

The `k6/timers` module provides standard JavaScript timer functions for scheduling asynchronous operations within k6 tests.

## Functions

### setTimeout()

Schedules a function to be executed after a specified delay.

<ParamField path="callback" type="function" required>
  Function to execute after the delay
</ParamField>

<ParamField path="delay" type="number" required>
  Delay in milliseconds before executing the callback
</ParamField>

<ParamField path="...args" type="any">
  Optional arguments to pass to the callback function
</ParamField>

**Returns:** Timer ID that can be used with `clearTimeout()`

```javascript theme={null}
import { setTimeout } from "k6/timers";

export default function () {
  console.log("Starting test");
  
  setTimeout(() => {
    console.log("Executed after 2 seconds");
  }, 2000);
  
  setTimeout((msg) => {
    console.log(msg);
  }, 1000, "Hello from timer");
}
```

### clearTimeout()

Cancels a timeout previously established by calling `setTimeout()`.

<ParamField path="timeoutId" type="number" required>
  Timer ID returned by setTimeout()
</ParamField>

```javascript theme={null}
import { setTimeout, clearTimeout } from "k6/timers";

export default function () {
  const timeoutId = setTimeout(() => {
    console.log("This will not execute");
  }, 5000);
  
  // Cancel the timeout
  clearTimeout(timeoutId);
}
```

### setInterval()

Repeatedly calls a function with a fixed time delay between each call.

<ParamField path="callback" type="function" required>
  Function to execute repeatedly
</ParamField>

<ParamField path="delay" type="number" required>
  Delay in milliseconds between each execution
</ParamField>

<ParamField path="...args" type="any">
  Optional arguments to pass to the callback function
</ParamField>

**Returns:** Interval ID that can be used with `clearInterval()`

```javascript theme={null}
import { setInterval, clearInterval } from "k6/timers";
import { sleep } from "k6";

export default function () {
  let count = 0;
  
  const intervalId = setInterval(() => {
    count++;
    console.log(`Interval execution #${count}`);
    
    if (count >= 5) {
      clearInterval(intervalId);
    }
  }, 1000);
  
  sleep(6); // Keep VU alive to see interval executions
}
```

### clearInterval()

Cancels a timed, repeating action previously established by calling `setInterval()`.

<ParamField path="intervalId" type="number" required>
  Interval ID returned by setInterval()
</ParamField>

```javascript theme={null}
import { setInterval, clearInterval } from "k6/timers";

export default function () {
  const intervalId = setInterval(() => {
    console.log("This executes every second");
  }, 1000);
  
  // Stop after 5 seconds
  setTimeout(() => {
    clearInterval(intervalId);
    console.log("Interval stopped");
  }, 5000);
}
```

## Real-World Example

Based on the k6 source example showing timer behavior:

```javascript theme={null}
import { setTimeout } from "k6/timers";

let last = 0;
let iterations = 10;

function timeout() {
  // Log the time of this call
  logline(new Date().getMilliseconds());
  
  // If we are not finished, schedule the next call
  if (iterations-- > 0) {
    setTimeout(timeout, 0);
  }
}

export default function () {
  // Initialize iteration count and the starting timestamp
  iterations = 10;
  last = new Date().getMilliseconds();
  
  // Start timer
  setTimeout(timeout, 0);
}

function pad(number) {
  return number.toString().padStart(3, "0");
}

function logline(now) {
  // Log the last timestamp, the new timestamp, and the difference
  console.log(`${pad(last)}         ${pad(now)}          ${now - last}`);
  last = now;
}
```

## Important Notes

<Warning>
  Timer functions in k6 are executed within the VU context. Unlike browser JavaScript, timers do not extend the VU iteration time beyond the default function execution.
</Warning>

<Note>
  These are the same timer functions available globally in browsers. The `k6/timers` module explicitly exports them for use in k6 scripts.
</Note>

<Tip>
  Use timers to simulate real-world scenarios like polling, periodic checks, or delayed actions within your load tests.
</Tip>

## Use Cases

* **Simulating user behavior**: Add realistic delays between actions
* **Polling endpoints**: Check status at regular intervals
* **Cleanup operations**: Schedule cleanup after test actions
* **Asynchronous workflows**: Coordinate multiple async operations

## Related Resources

* [k6 Core Module](/javascript-api/k6)
* [Test Lifecycle](/concepts/test-lifecycle)
* [Virtual Users](/concepts/virtual-users)
