去抖动函数 和 节流函数的思考

时间:2021-07-14 15:04:46

<!DOCTYPE html >
<html lang = "en" >
<head >
<meta charset = "UTF-8" >
<title >Document < /title>
</head >
<body style = "height: 3000px;" >
<script >
var i = 0 ;
var _ ={}
var limit = (func , wait , debounce) =>{
var timeout ;
return function() {
var context = this ,
args = arguments ;
var throttler = function() {
timeout = null ;
func. apply(context , args)
};

if( debounce ) {
clearTimeout( timeout ) ;
};
if( debounce || !timeout ) {
timeout = setTimeout(throttler ,wait)
};
}
}

// 节流函数 只调用一次
_. throttler = function (func , wait) {
return limit(func , wait , false)
}

//多次调用,只执行最后一次请求
_. debounce = function(func , wait) {
return limit(func , wait , true)
}
// window.addEventListener('scroll',
// _.throttler(function(){
// console.log(i++)
// },250,false)
// )
window. addEventListener( 'scroll' ,
_. debounce( function() {
console. log(i ++ )
}, 250 , false)
)
< /script>
</body >
< /html>