Defer Heavy Work With Idle Callback
ReactJS
Hard
7 views
Problem Description
Run heavy work when the browser is idle so UI stays responsive.
Output Format
Render a React component.
Constraints
Use requestIdleCallback with a fallback to setTimeout.
Official Solution
import React, { useRef, useState } from 'react';
function heavyText() {
let out = '';
for (let i = 0; i < 12000; i++) out += String.fromCharCode(97 + (i % 26));
return out.slice(0, 240) + '... meetcode';
}
export default function App() {
const [status, setStatus] = useState('idle');
const [result, setResult] = useState('');
const handleRef = useRef(null);
function run() {
setStatus('scheduled');
setResult('');
const cb = () => {
setStatus('running');
const r = heavyText();
setResult(r);
setStatus('done');
};
if (typeof window.requestIdleCallback === 'function') {
handleRef.current = window.requestIdleCallback(cb, { timeout: 600 });
return;
}
handleRef.current = setTimeout(cb, 0);
}
function cancel() {
const h = handleRef.current;
if (!h) return;
if (typeof window.cancelIdleCallback === 'function') window.cancelIdleCallback(h);
else clearTimeout(h);
handleRef.current = null;
setStatus('cancelled');
}
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>Idle work</h2>
<div style={{ display: 'flex', gap: 10 }}>
<button type='button' onClick={run} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Run</button>
<button type='button' onClick={cancel} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Cancel</button>
</div>
<div style={{ marginTop: 10, color: '#555' }}>Status: {status}</div>
<div style={{ marginTop: 10, border: '1px solid #eee', borderRadius: 14, padding: 12, minHeight: 80 }}>{result || 'No result yet.'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!