-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottling.js
More file actions
28 lines (25 loc) · 802 Bytes
/
throttling.js
File metadata and controls
28 lines (25 loc) · 802 Bytes
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
// Throttling in JavaScript
const expensive = ()=>{
console.log('It is expensive and you should know its worth')
}
// This will fire even for a little amount of px
// window.addEventListener('resize', betterExpensive)
// We need to throttle this and write a better expensive function
const throttled = (func,limit)=>{
let flag = true
return function(){
// if that expensive function is somehow taking some arguments or point to this also then we got this
let context = this,
args = arguments
if(flag){
func.apply(context,args)
flag = false
setTimeout(()=>{
flag = true
},limit)
}
}
}
let betterExpensive = throttled(expensive,500)
// This is now much better
window.addEventListener('resize', betterExpensive)