Member-only story
Source: Difference between debounce and setTimeout
For more questions and answers visit our website at Frontend Interview Questions
Debouncing is a technique used in JavaScript to limit the frequency of a function call that gets triggered repeatedly within a short period. It is often used in scenarios where an event (such as scrolling,resizing or api calls with search input change) can trigger frequent function calls, but you want to ensure that the function is only executed once after a certain delay when the event has stopped.
Code to implement ‘Debounce’ in Javascript:
HTML code:
<input type="text" onkeyup="search()">
JavaScript code:
let timerId;
let delay=1000;
function debounce(callback, delay) {
if(timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(()=>{
callback();
},delay)
}
function api() {
console.log('api call code here');
}
function search() {
debounce(api, delay);
}
setTimeout, on the other hand, is a built-in JavaScript function that schedules the execution of a function after a specified delay. It is commonly used for tasks that need to be performed after a certain period, such as animations, timeouts, or delayed operations.