|
1 | 1 | ---
|
2 |
| -title: "k6/timers" |
3 |
| -description: "k6 timers API" |
| 2 | +title: 'k6/timers' |
| 3 | +description: 'k6 timers API' |
4 | 4 | weight: 11
|
5 | 5 | ---
|
6 | 6 |
|
7 | 7 | # k6/timers
|
8 | 8 |
|
9 | 9 | Implement timers to work with k6's event loop. They mimic the functionality found in browsers and other JavaScript runtimes.
|
10 | 10 |
|
11 |
| -| Function | Description | |
12 |
| -| :------------------------------------------ | :--------------------------------------------------------------------------------------------- | |
13 |
| -| [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) | Sets a function to be run after a given timeout. | |
14 |
| -| [clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) | Clears a previously set timeout with `setTimeout`. | |
15 |
| -| [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) | Sets a function to be run on a given interval. | |
| 11 | +| Function | Description | |
| 12 | +| :---------------------------------------------------------------------------- | :--------------------------------------------------- | |
| 13 | +| [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) | Sets a function to be run after a given timeout. | |
| 14 | +| [clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) | Clears a previously set timeout with `setTimeout`. | |
| 15 | +| [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) | Sets a function to be run on a given interval. | |
16 | 16 | | [clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) | Clears a previously set interval with `setInterval`. |
|
| 17 | + |
| 18 | +{{% admonition type="note" %}} |
| 19 | + |
| 20 | +The timing methods are available globally, like in other JavaScript runtimes, and it is unnecessary to import them from the `k6/timers` module. |
| 21 | + |
| 22 | +{{% /admonition %}} |
| 23 | + |
| 24 | +## Example |
| 25 | + |
| 26 | +```javascript |
| 27 | +export default function () { |
| 28 | + const intervalId = setInterval(() => { |
| 29 | + console.log('This runs every 200ms'); |
| 30 | + }, 200); |
| 31 | + |
| 32 | + const timeoutId = setTimeout(() => { |
| 33 | + console.log('This runs after 2s'); |
| 34 | + |
| 35 | + // clear the timeout and interval to exit k6 |
| 36 | + clearInterval(intervalId); |
| 37 | + clearTimeout(timeoutId); |
| 38 | + }, 2000); |
| 39 | +} |
| 40 | +``` |
0 commit comments