Debounce function in JavaScript
Mahmudul Hasan
Software Engineer at PETRONAS | JavaScript, React, Node, Typescript, AWS, Python , Data Structure, Algorithm, Web Performance and Optimization
?? The?debounce()?function?forces a function to wait a certain amount of time against an event. When an event occurs, it starts to wait a certain amount of time to execute an debounced function .But during the waiting time if another event occurs, it will reset the previous waiting time and start to wait again for the newly created event.
??Prerequisite to understand debounce() method
??closure ?? setTimeout
领英推荐
<!DOCTYPE html
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta http-equiv="X-UA-Compatible" content="IE=edge">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <title>Document</title>
</head>
<body>
? ? <input type="text" class="input">
? ? <script src="./index.js"></script>
</body>
</html>
const inputElement = document.querySelector('.input')
function fetch(...args){
? ? const [event, ...rest] = args ;
? ? console.log('api calling.....', event.target.value)
}
function debounce(fn, ?delay){
? ? let tm ;
? ? return function(...args){
? ? ? ? clearTimeout(tm);
? ? ? ? const that = this ;
? ? ? ? tm = setTimeout(()=>{
? ? ? ? ? ? fn.apply(that, args);
? ? ? ? }, delay)
? ? }
? ?
}
const debounceForEvent = debounce(fetch, ?500);
inputElement.addEventListener('keyup', debounceForEvent);;