#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:

  1. Asynchronous Execution:
    • Places callback on the event queue after the specified timeout.
  2. Non-Blocking:
    • Allows program execution to continue while waiting for the timeout.
  3. Minimum Delay:
    • Actual delay may be longer than specified due to JavaScript's single-threaded nature and browser limitations.

Why It Matters:


How to Implement:

  1. Basic Usage:
    • const timerId = setTimeout(callback, delayInMs);
  2. With Parameters:
    • setTimeout(callback, delayInMs, param1, param2, ...);
  3. Cancellation:
    • clearTimeout(timerId); to prevent execution if needed.

Example:

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));
```


Connections:


References:

  1. Primary Source:
    • MDN Web Docs, Window.setTimeout()
  2. Additional Resources:

Tags:

#JavaScript #Asynchronous #setTimeout #Timing #EventLoop #Debouncing


Connections:


Sources: