k6/timers module implements timer functions that work with k6’s event loop. These functions mimic the functionality found in browsers and other JavaScript runtimes.
Overview
Use timer functions to schedule code execution at specific times or intervals within your k6 tests. These are particularly useful for:- Simulating user think time with delays
- Creating periodic actions (polling, heartbeats)
- Implementing timeouts for WebSocket or browser tests
- Controlling test flow and timing
Timer functions are available globally in k6 scripts. You don’t need to import them unless you prefer explicit imports.
Importing the Module
API Reference
setTimeout
function
Schedules a function to run after a specified delay.Parameters:Returns:
function
required
Function to execute after the delay
number
required
Delay in milliseconds before executing the callback
...any
Optional arguments to pass to the callback function
number
Timeout identifier that can be used with
clearTimeout()clearTimeout
function
Cancels a timeout previously established by calling
setTimeout().Parameters:number
required
The timeout identifier returned by
setTimeout()setInterval
function
Schedules a function to run repeatedly at specified intervals.Parameters:Returns:
function
required
Function to execute at each interval
number
required
Time in milliseconds between each execution
...any
Optional arguments to pass to the callback function
number
Interval identifier that can be used with
clearInterval()clearInterval
function
Cancels an interval previously established by calling
setInterval().Parameters:number
required
The interval identifier returned by
setInterval()Examples
Basic Timeout Example
Basic Interval Example
WebSocket Heartbeat
Browser Test with Timeout
Simulating User Think Time
Polling Pattern
Cancelling Timers
Best Practices
Always Clear Timers
Always Clear Timers
Always clear intervals and timeouts when they’re no longer needed to prevent memory leaks and unexpected behavior.
Use sleep() for Simple Delays
Use sleep() for Simple Delays
For simple delays in the default function, use
sleep() from k6 instead of setTimeout(). It’s more straightforward and doesn’t require event loop handling.Event Loop Requirement
Event Loop Requirement
Timers require an active event loop. They work best in:
- WebSocket tests (using
k6/websockets) - Browser tests (using
k6/browser) - Scenarios with long-running connections
Precision Considerations
Precision Considerations
Timer precision is not guaranteed. Actual execution may be delayed if:
- The event loop is busy
- System resources are limited
- Other operations are blocking
Timers vs sleep()
Related Resources
sleep()
Simple blocking delay function
k6/websockets
WebSocket API that works with timers
k6/browser
Browser API that uses timers
MDN: Timers
Browser timer API documentation