#atom
setTimeout - Executing Code After a Specified Delay
Core Idea:
The setTimeout function schedules a callback function to execute once after a specified delay, providing a way to defer execution of code without blocking the main thread.
Key Principles:
- Asynchronous Execution:
- Places callback on the event queue after the specified timeout.
- Non-Blocking:
- Allows program execution to continue while waiting for the timeout.
- Minimum Delay:
- Actual delay may be longer than specified due to JavaScript's single-threaded nature and browser limitations.
Why It Matters:
- Deferred Execution:
- Enables scheduling tasks to run in the future without blocking.
- User Experience:
- Allows time-dependent behaviors like debouncing and delays.
- Performance Management:
- Can break up long-running tasks to prevent UI freezing.
How to Implement:
- Basic Usage:
const timerId = setTimeout(callback, delayInMs);
- With Parameters:
setTimeout(callback, delayInMs, param1, param2, ...);
- Cancellation:
clearTimeout(timerId);
to prevent execution if needed.
Example:
-
Scenario:
- Implementing a search input with debouncing to reduce API calls.
-
Application:
function debounceSearch(searchFn, delay = 300) {
let timeoutId;
return function(query) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
searchFn(query);
}, delay);
};
}
const debouncedSearch = debounceSearch(fetchSearchResults);
searchInput.addEventListener('input', e => debouncedSearch(e.target.value));
```
- Result:
- API calls are only made after user stops typing for 300ms, reducing server load.
Connections:
- Related JavaScript Concepts:
- setInterval: For repeated executions.
- requestAnimationFrame: For visual updates.
- Broader Programming Concepts:
- Event Loop: Timing and execution order in JavaScript.
- Debouncing & Throttling: Controlling execution frequency.
References:
- Primary Source:
- MDN Web Docs, Window.setTimeout()
- Additional Resources:
Tags:
#JavaScript #Asynchronous #setTimeout #Timing #EventLoop #Debouncing
Connections:
Sources:
- From: AG Grid