### Install worker-timers using npm Source: https://github.com/chrisguttandin/worker-timers/blob/master/README.md Install the worker-timers package using npm. This is the first step to using the library in your project. ```shell npm install worker-timers ``` -------------------------------- ### Schedule a one-time callback with setTimeout Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Use worker-timers' setTimeout to schedule a function to run once after a delay, unaffected by tab throttling. The example logs the elapsed time. ```javascript import { setTimeout, clearTimeout } from 'worker-timers'; const before = performance.now(); const timeoutId = setTimeout(() => { const elapsed = performance.now() - before; console.log(`Called after ${Math.round(elapsed)}ms`); // Even if the tab was backgrounded, elapsed will be ~300ms }, 300); ``` -------------------------------- ### Import worker-timers functions Source: https://github.com/chrisguttandin/worker-timers/blob/master/README.md Import the necessary timer functions from the worker-timers package. These functions have the same signatures as their global counterparts. ```javascript import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers'; ``` -------------------------------- ### Basic Usage of worker-timers Source: https://github.com/chrisguttandin/worker-timers/blob/master/README.md Use setInterval and setTimeout with worker-timers just like the native functions. Remember to use clearInterval and clearTimeout to manage the timers. ```javascript const intervalId = setInterval(() => { // do something many times }, 100); clearInterval(intervalId); const timeoutId = setTimeout(() => { // do something once }, 100); clearTimeout(timeoutId); ``` -------------------------------- ### Server-Side Rendering (SSR) Safe Timer Abstraction Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Conditionally import worker-timers in browser environments and fall back to native timers on the server to ensure SSR compatibility. ```javascript // timer-utils.js — SSR-safe timer abstraction let setIntervalFn, clearIntervalFn, setTimeoutFn, clearTimeoutFn; if (typeof window !== 'undefined' && typeof Worker !== 'undefined') { // Browser: use worker-timers for throttling-free behavior ({ setInterval: setIntervalFn, clearInterval: clearIntervalFn, setTimeout: setTimeoutFn, clearTimeout: clearTimeoutFn } = await import('worker-timers')); } else { // Server / Node.js: fall back to native timers setIntervalFn = globalThis.setInterval.bind(globalThis); clearIntervalFn = globalThis.clearInterval.bind(globalThis); setTimeoutFn = globalThis.setTimeout.bind(globalThis); clearTimeoutFn = globalThis.clearTimeout.bind(globalThis); } export { setIntervalFn as setInterval, clearIntervalFn as clearInterval, setTimeoutFn as setTimeout, clearTimeoutFn as clearTimeout }; ``` -------------------------------- ### Replace Native Timers Globally with worker-timers Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Import and reassign native timer functions to use worker-timers. This affects the entire page scope and should be used with caution. ```javascript import * as workerTimers from 'worker-timers'; // Option 1: use as named imports (recommended) const { setInterval, clearInterval, setTimeout, clearTimeout } = workerTimers; // Option 2: replace globals (use with caution — affects entire page scope) window.setInterval = workerTimers.setInterval; window.clearInterval = workerTimers.clearInterval; window.setTimeout = workerTimers.setTimeout; window.clearTimeout = workerTimers.clearTimeout; // All subsequent code using setInterval/setTimeout now runs unthrottled const id = setInterval(() => console.log('unthrottled'), 100); setTimeout(() => clearInterval(id), 600); ``` -------------------------------- ### Repeatedly call a function with setInterval Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Use worker-timers' setInterval to call a function every 500ms, regardless of tab focus. The interval is cleared after 5 calls. ```javascript import { setInterval, clearInterval } from 'worker-timers'; // Call a function every 500ms, regardless of tab focus state let count = 0; const intervalId = setInterval(() => { count += 1; console.log(`Tick #${count} at ${new Date().toISOString()}`); if (count >= 5) { clearInterval(intervalId); console.log('Interval cleared after 5 ticks.'); } }, 500); ``` -------------------------------- ### Angular/Zone.js Integration with Manual Change Detection Source: https://context7.com/chrisguttandin/worker-timers/llms.txt When using worker-timers in Angular, manually trigger change detection within timer callbacks using `NgZone.run()` because Zone.js is unaware of worker-timers. ```typescript import { Component, NgZone, OnDestroy } from '@angular/core'; import { setInterval, clearInterval } from 'worker-timers'; @Component({ selector: 'app-clock', template: '{{ time }}' }) export class ClockComponent implements OnDestroy { time = ''; private intervalId: number; constructor(private zone: NgZone) { // Run outside Angular zone to schedule the timer this.intervalId = setInterval(() => { // Re-enter Angular zone so change detection fires this.zone.run(() => { this.time = new Date().toLocaleTimeString(); }); }, 1000); } ngOnDestroy(): void { clearInterval(this.intervalId); } } ``` -------------------------------- ### setTimeout Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Schedules a function to be called once after a specified delay, unaffected by background tab throttling. Returns a unique timer ID. ```APIDOC ## setTimeout(func, delay, ...args) ### Description Schedules `func` to be called once after `delay` milliseconds, unaffected by tab throttling. Returns a numeric timer ID. ### Parameters - `func` (function) - The function to execute. - `delay` (number) - The delay in milliseconds. - `...args` (any) - Additional arguments to pass to the function. ### Returns - (number) - A numeric timer ID. ### Example ```javascript import { setTimeout, clearTimeout } from 'worker-timers'; const timeoutId = setTimeout(() => { console.log('This will be called after 300ms.'); }, 300); // To cancel before it fires: // clearTimeout(timeoutId); ``` ``` -------------------------------- ### setInterval Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Schedules a function to be called repeatedly at a specified interval, unaffected by background tab throttling. Returns a unique timer ID. ```APIDOC ## setInterval(func, delay, ...args) ### Description Schedules `func` to be called repeatedly with `delay` milliseconds between each invocation, even when the browser tab is in the background. Returns a numeric timer ID that can be passed to `clearInterval()`. ### Parameters - `func` (function) - The function to execute. - `delay` (number) - The interval in milliseconds. - `...args` (any) - Additional arguments to pass to the function. ### Returns - (number) - A numeric timer ID. ### Example ```javascript import { setInterval, clearInterval } from 'worker-timers'; let count = 0; const intervalId = setInterval(() => { count += 1; console.log(`Tick #${count}`); if (count >= 5) { clearInterval(intervalId); } }, 500); ``` ``` -------------------------------- ### worker-timers vs. WindowTimers clear functions Source: https://github.com/chrisguttandin/worker-timers/blob/master/README.md worker-timers maintains separate lists for intervals and timeouts, unlike native WindowTimers. clearTimeout will not cancel an interval set with worker-timers' setInterval. ```javascript const periodicWork = () => {}; // This will stop the interval. const windowId = window.setInterval(periodicWork, 100); window.clearTimeout(windowId); // This will not cancel the interval. It may cancel a timeout. const workerId = setInterval(periodicWork, 100); clearTimeout(workerId); ``` -------------------------------- ### clearInterval Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Cancels a repeated callback previously scheduled with worker-timers' setInterval. The timerId must be from worker-timers. ```APIDOC ## clearInterval(timerId) ### Description Cancels the interval previously scheduled with `worker-timers`' `setInterval()`. The `timerId` must originate from `worker-timers`' own `setInterval`; interval IDs and timeout IDs are tracked separately. ### Parameters - `timerId` (number) - The timer ID returned by `setInterval()`. ### Example ```javascript import { setInterval, clearInterval } from 'worker-timers'; const intervalId = setInterval(() => { console.log('This will only run once.'); clearInterval(intervalId); }, 200); ``` ``` -------------------------------- ### Cancel a timeout with clearTimeout Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Cancel a timeout scheduled with worker-timers' setTimeout before it fires. Passing an interval ID will not cancel the interval. ```javascript import { setTimeout, clearTimeout } from 'worker-timers'; const timeoutId = setTimeout(() => { console.log('This will never run.'); }, 1000); // Cancel the timeout before it fires clearTimeout(timeoutId); console.log('Timeout cancelled.'); ``` -------------------------------- ### Cancel an interval with clearInterval Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Cancel an interval scheduled with worker-timers' setInterval. Note that IDs are not interchangeable with native timer IDs or timeout IDs. ```javascript import { setInterval, clearInterval } from 'worker-timers'; const intervalId = setInterval(() => { console.log('This will only run once.'); // Cancel immediately after the first call clearInterval(intervalId); }, 200); ``` -------------------------------- ### clearTimeout Source: https://context7.com/chrisguttandin/worker-timers/llms.txt Cancels a one-time callback previously scheduled with worker-timers' setTimeout. The timerId must be from worker-timers. ```APIDOC ## clearTimeout(timerId) ### Description Cancels a timeout previously scheduled with `worker-timers`' `setTimeout()`. Must only be called with IDs returned by `worker-timers`' `setTimeout`; passing an interval ID will not cancel the interval. ### Parameters - `timerId` (number) - The timer ID returned by `setTimeout()`. ### Example ```javascript import { setTimeout, clearTimeout } from 'worker-timers'; const timeoutId = setTimeout(() => { console.log('This will never run.'); }, 1000); clearTimeout(timeoutId); console.log('Timeout cancelled.'); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.