Asynchronous JavaScript in LWC · Lesson 16 of 25
Timers in LWC: setTimeout, setInterval and Cleanup
Timers are simple to start and easy to forget. A forgotten setInterval keeps calling Apex after the user has navigated away; a setTimeout used to "wait for the DOM" works on your laptop and fails on a slow one. This lesson shows the legitimate uses of timers in components and the habits that keep them safe.
In this lesson
- setTimeout, setInterval and their clear functions
- An auto-dismissing message
- Polling with backoff – and when not to poll
- requestAnimationFrame and the lint rule
The timer functions
const once = setTimeout(() => console.log('timeout fired (after 150ms)'), 150);
const cancelled = setTimeout(() => console.log('never runs'), 50);
clearTimeout(cancelled); // cancel before it fires
let ticks = 0;
const repeat = setInterval(() => {
ticks++;
console.log(`tick ${ticks} (every 30ms)`);
if (ticks === 3) clearInterval(repeat); // stop it, or it runs forever
}, 30);
console.log('timers are scheduled; the code carries on');
timers are scheduled; the code carries on tick 1 (every 30ms) tick 2 (every 30ms) tick 3 (every 30ms) timeout fired (after 150ms)
Both functions return an id; keep it in a field so you can clear the timer later. The delay is a minimum: a busy page or a background tab can delay callbacks, and browsers slow timers in hidden tabs.
An auto-dismissing message
// saveBanner.js
import { LightningElement } from 'lwc';
const HIDE_AFTER = 200; // ms (a real banner would use ~3000)
export default class SaveBanner extends LightningElement {
message = '';
hideTimer;
handleSave() {
this.message = 'Changes saved';
clearTimeout(this.hideTimer); // restart the countdown on repeated saves
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.hideTimer = setTimeout(() => {
this.message = '';
}, HIDE_AFTER);
}
disconnectedCallback() {
clearTimeout(this.hideTimer);
}
get hasMessage() {
return this.message !== '';
}
}
<!-- saveBanner.html -->
<template>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
<template lwc:if={hasMessage}><p>✓ {message}</p></template>
</template>
[Save] › click “Save” [Save] ✓ Changes saved › wait 120ms [Save] ✓ Changes saved › wait 150ms [Save]
For standard notifications you'd normally use a toast (lightning/toast or ShowToastEvent), which dismisses itself. A custom timer is for inline messages and your own UI.
Polling with backoff
Sometimes you have to wait for the server – a batch job, an external integration. Poll, but slow down over time and stop eventually:
// simulated job status: done on the 4th check
let checks = 0;
const getJobStatus = async () => (++checks >= 4 ? 'Completed' : 'Processing');
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitForJob({ firstDelay = 10, maxDelay = 80, maxChecks = 6 } = {}) {
let delayMs = firstDelay;
for (let i = 1; i <= maxChecks; i++) {
const status = await getJobStatus();
console.log(`check ${i}: ${status} (next wait ${delayMs}ms)`);
if (status === 'Completed') return status;
await wait(delayMs);
delayMs = Math.min(delayMs * 2, maxDelay); // exponential backoff with a ceiling
}
throw new Error('Job is taking too long – check again later');
}
console.log(await waitForJob());
check 1: Processing (next wait 10ms) check 2: Processing (next wait 20ms) check 3: Processing (next wait 40ms) check 4: Completed (next wait 80ms) Completed
Prefer push over polling
Every poll is an Apex call counted against limits. If the server can tell you when something changes, use that instead: Platform Events or Change Data Capture via lightning/empApi, or Lightning Message Service for changes from other components on the same page.
requestAnimationFrame and the lint rule
requestAnimationFrame(callback)runs just before the next screen repaint – the right tool for smooth visual updates (progress animations, measuring layout), cancelled withcancelAnimationFrame.- LWC's ESLint rule
@lwc/lwc/no-async-operationflagssetTimeout,setIntervalandrequestAnimationFrame. It's a reminder, not a ban: if the timer has a real purpose (debounce, clock, auto-dismiss, polling), disable it for that line with a comment. - If you're using a timer to wait for rendering, use
renderedCallbackinstead.
| Need | Use |
|---|---|
| Run once after a pause (search, auto-save) | debounced setTimeout |
| Update a clock or countdown | setInterval, cleared in disconnectedCallback |
| Wait for a server job | polling with backoff – or Platform Events |
| Animate or measure layout | requestAnimationFrame |
| Work with the rendered DOM | renderedCallback, not a timer |
Practice
Try it yourself
Users report that the "time since last update" label keeps counting after they close the record tab, and the browser gets slower. What's missing?
Show answer
The
setIntervalis never cleared. Store its id in a field and callclearInterval(this.intervalId)indisconnectedCallback.Why does
setTimeout(() => this.template.querySelector('input').focus(), 0)sometimes fail?Show answer
It guesses that rendering is done after one task. Under load or with nested components it may not be. Focus the input in
renderedCallback, guarded so it runs only when needed.
Quick check
How do you stop a setInterval?
clearInterval with the id it returned.
Is the delay in setTimeout exact?
No – it is a minimum; callbacks can run later.
Where do you clear timers in a component?
disconnectedCallback.
Summary
- Store timer ids in fields and clear them in disconnectedCallback.
- Restart timers with clearTimeout before setting a new one.
- Poll with backoff and a limit – or use Platform Events instead.
- Don't use timers to wait for rendering; use renderedCallback.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.