Debounce function in JavaScript

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

要查看或添加评论,请登录

Mahmudul Hasan的更多文章

社区洞察

其他会员也浏览了