js 防抖 节流
debounce(防抖)
触发高频时间后n秒内函数只会执行一次, 如果n秒内高频时间再次触发, 则重新计算时间。 防抖常应用于用户进行搜索输入节约请求资源,window触发resize事件时进行防抖只触发一次。
const debounce = ( fn, time) => {
let timeout = null ;
return function ( ) {
clearTimeout ( timeout)
timeout = setTimeout ( ( ) => {
fn. apply ( this , arguments) ;
} , time) ;
}
} ;
throttle(节流)
高频时间触发, 但n秒内只会执行一次, 所以节流会稀释函数的执行频率。 节流常应用于鼠标不断点击触发、监听滚动事件。
const throttle = ( fn, time) => {
let flag = true ;
return function ( ) {
if ( ! flag) return ;
flag = false ;
setTimeout ( ( ) => {
fn. apply ( this , arguments) ;
flag = true ;
} , time) ;
}
}
demo
< input type= "text" id= "oipt" >
< script>
var oipt = document. getElementById ( 'oipt' )
function debounce ( time, callback) {
let timer = null
return function ( value, ) {
clearTimeout ( timer)
timer = setTimeout ( function ( ) {
callback ( value)
} , time)
}
}
var debounceFn = debounce ( 1000 , debounceCallBack)
function debounceCallBack ( value) {
console. log ( value)
}
oipt. addEventListener ( 'keyup' , function ( e) {
debounceFn ( e. target. value)
} )
< button id= "obtn" > 点击< / button>
< script>
function clickFn ( ) {
console. log ( Math. random ( ) )
}
function thro ( time, func) {
let timerout
return function ( ) {
if ( ! timerout) {
timerout = setTimeout ( function ( ) {
func ( )
timerout = null
} , time)
}
}
}
document. getElementById ( 'obtn' ) . onclick = thro ( 1000 , clickFn)
< / script>