How to Implement Auto Refresh in JavaScript (Step-by-Step)
Auto-refresh can keep data current without user action — useful for dashboards, live feeds, or development pages. Below are clear, actionable steps to implement safe, efficient auto refresh in JavaScript with examples and best practices.
1. Choose the refresh approach
- Full page reload — reloads entire document (simple, heavier).
- Partial update (AJAX / Fetch) — requests only needed data and updates DOM (preferred for performance).
- WebSockets / Server-Sent Events — push updates from server (best for real-time, avoids polling).
This guide focuses on full-page reload and Fetch-based partial updates.
2. Full page reload (simple)
Use setInterval with location.reload(). Example:
javascript
// Reload every 30 seconds const intervalMs = 30000; const reloadId = setInterval(() => { // false forces reload from cache; true forces reload from server location.reload(true); }, intervalMs); // To stop auto-refresh later: // clearInterval(reloadId);
Notes:
- setInterval runs repeatedly; clearInterval stops it.
- location.reload(true) is deprecated in some browsers; use location.reload() and control caching via server headers.
3. Partial updates with fetch (recommended)
Fetch only required data and update DOM to reduce bandwidth and avoid flicker.
Example: refresh a JSON endpoint every 15 seconds and update a list.
javascript
const intervalMs = 15000; let fetchId = null; async function updateData() { try { const resp = await fetch(’/api/latest-items’, { cache: ‘no-store’ }); if (!resp.ok) throw new Error(</span><span class="token template-string" style="color: rgb(163, 21, 21);">HTTP </span><span class="token template-string interpolation interpolation-punctuation" style="color: rgb(57, 58, 52);">${</span><span class="token template-string interpolation">resp</span><span class="token template-string interpolation" style="color: rgb(57, 58, 52);">.</span><span class="token template-string interpolation">status</span><span class="token template-string interpolation interpolation-punctuation" style="color: rgb(57, 58, 52);">}</span><span class="token template-string template-punctuation" style="color: rgb(163, 21, 21);">); const data = await resp.json(); // Example DOM update const list = document.getElementById(‘items’); list.innerHTML = data.items.map(i =></span><span class="token template-string" style="color: rgb(163, 21, 21);"><li></span><span class="token template-string interpolation interpolation-punctuation" style="color: rgb(57, 58, 52);">${</span><span class="token template-string interpolation" style="color: rgb(57, 58, 52);">escapeHtml</span><span class="token template-string interpolation" style="color: rgb(57, 58, 52);">(</span><span class="token template-string interpolation">i</span><span class="token template-string interpolation" style="color: rgb(57, 58, 52);">.</span><span class="token template-string interpolation">name</span><span class="token template-string interpolation" style="color: rgb(57, 58, 52);">)</span><span class="token template-string interpolation interpolation-punctuation" style="color: rgb(57, 58, 52);">}</span><span class="token template-string" style="color: rgb(163, 21, 21);"></li></span><span class="token template-string template-punctuation" style="color: rgb(163, 21, 21);">).join(“); } catch (err) { console.error(‘Update failed:’, err); } } function startAutoRefresh() { updateData(); // initial load fetchId = setInterval(updateData, intervalMs); } function stopAutoRefresh() { if (fetchId) clearInterval(fetchId); } // Utility to prevent XSS function escapeHtml(s) { return s.replace(/[&<>”‘]/g, c => ({’&’:’&’,’<’:’<’,’>’:’>’,’“’:’”’,”‘”:”’}[c])); } // Start startAutoRefresh();
Tips:
- Use cache: ‘no-store’ to avoid stale responses.
- Provide user feedback (loading indicator, last-updated timestamp).
4. Debounce, backoff, and error handling
- Implement exponential backoff on consecutive failures to avoid hammering the server.
- Stop refresh when page is hidden to save resources using the Page Visibility API:
javascript
document.addEventListener(‘visibilitychange’, () => { if (document.hidden) stopAutoRefresh(); else startAutoRefresh(); });
5. Respect user control
- Provide UI to enable/disable auto-refresh and set interval. Example controls:
- Toggle switch for on/off
- Slider or select for interval (5s, 15s, 30s, 1m)
- Manual refresh button
6. Accessibility and UX
- Announce content updates for assistive tech (ARIA live regions):
html
<div id=“live” aria-live=“polite”></div>
- Avoid abrupt focus shifts when updating DOM.
7. Security and performance considerations
- Sanitize data before inserting into DOM to prevent XSS.
- Limit minimum interval (e.g., >= 5s) to avoid excessive load.
- Use ETag/If-Modified-Since or conditional requests on server to reduce payloads.
- For high-frequency real-time updates, prefer WebSockets or Server-Sent Events.
8. Example: combined UI + fetch
html
<button id=“toggle”>Stop</button> <select id=“interval”> <option value=“5000”>5s</option> <option value=“15000” selected>15s</option> <option value=“30000”>30s</option> </select> <ul id=“items”></ul> <script> let intervalMs = 15000; let timer = null; const toggleBtn = document.getElementById(‘toggle’); const sel = document.getElementById(‘interval’); async function fetchAndUpdate() { try { const r = await fetch(’/api/latest-items’, { cache:‘no-store’ }); if (!r.ok) throw new Error(r.status); const {items} = await r.json(); document.getElementById(‘items’).innerHTML = items.map(i=></span><span class="token script language-javascript template-string" style="color: rgb(163, 21, 21);"><li></span><span class="token script language-javascript template-string interpolation interpolation-punctuation">${</span><span class="token script language-javascript template-string interpolation">i</span><span class="token script language-javascript template-string interpolation">.</span><span class="token script language-javascript template-string interpolation">name</span><span class="token script language-javascript template-string interpolation interpolation-punctuation">}</span><span class="token script language-javascript template-string" style="color: rgb(163, 21, 21);"></li></span><span class="token script language-javascript template-string template-punctuation">).join(“); } catch(e) { console.error(e); } } function start() { fetchAndUpdate(); timer = setInterval(fetchAndUpdate, intervalMs); toggleBtn.textContent = ‘Stop’; } function stop() { clearInterval(timer); timer = null; toggleBtn.textContent = ‘Start’; } toggleBtn.addEventListener(‘click’, () => timer ? stop() : start()); sel.addEventListener(‘change’, e => { intervalMs = Number(e.target.value); if (timer) { stop(); start(); } }); // auto-start start(); </script>
9. When to use push instead of polling
- Use WebSockets or Server-Sent Events if updates are frequent, latency-sensitive, or you want to avoid polling overhead.
Summary
- Prefer partial updates with fetch for efficiency.
- Provide user control, handle visibility, and implement backoff on errors.
- For true real-time, use push technologies.
Leave a Reply