-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeBouncing.js
More file actions
71 lines (57 loc) · 1.63 KB
/
deBouncing.js
File metadata and controls
71 lines (57 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const myInput= document.getElementById('input-event')
const btn= document.getElementById('btn')
//Trailing debouncing
//calling function only after the timeout is completed
function debounce(func,delay){
let timeId;
return function(...args){
if(timeId){
clearTimeout(timeId)
}
timeId=setTimeout(()=>{
func.call(this, ...args)
},delay)
}
}
//leading debouncing
//always runs function first time and then runs when the user rest the keys
function leadingDebouncing(func,delay){
let timeId;
return function(...args){
if(!timeId){
func.call(this,...args)
}
clearTimeout(timeId);
timeId=setTimeout(()=>{
timeId=null;
},delay)
}
}
function findSuggestion(e){
console.log(e.target.value)
}
const decoratedFunc=debounce(findSuggestion,500)
myInput.addEventListener('input',decoratedFunc)
function handleClick(){
console.log(Math.random())
}
// btn.addEventListener('click',leadingDebouncing(handleClick,400))
btn.addEventListener('click',betterDebouncing(handleClick,400,{leading:true,trailing:true}))
//leading + trailling
function betterDebouncing(func,delay,option={leading:false,trailing:true}){
let timeId=null;
return function(...args){
let isInvoked=false;
if(!timeId && option.leading){
func.call(this,...args);
isInvoked=true;
}
clearTimeout(timeId);
timeId=setTimeout(()=>{
if(option.trailing && !isInvoked){
func.call(this,...args)
}
timeId=null;
},delay)
}
}