防抖
< body>
< input type= "text" id= "input" >
< script>
const inp = document. querySelector ( '#input' ) ;
inp. oninput = function ( ) {
console. log ( this . value) ;
}
< / script>
< / body>
需求就是过滤掉过于频繁的操作,只要最后的结果 利用计时器实现防抖
< body>
< input type= "text" id= "input" >
< script>
const inp = document. querySelector ( '#input' ) ;
let t = null ;
inp. oninput = function ( ) {
if ( t !== null ) {
clearTimeout ( t) ;
}
t= setTimeout ( ( ) => {
console. log ( this . value) ;
} , 500 )
}
< / script>
< / body>
使用闭包封装防抖函数
< body>
< input type= "text" id= "input" >
< script>
const inp = document. querySelector ( '#input' ) ;
inp. oninput = debource ( function ( ) {
console. log ( this . value) ;
} , 500 ) ;
function debource ( fn, delay ) {
let t = null ;
return function ( ) {
if ( t !== null ) {
clearTimeout ( t) ;
}
t= setTimeout ( ( ) => {
fn . call ( this ) ;
} , delay)
}
}
< / script>
< / body>
节流
节流函数的封装
< script>
window. onscroll = throttle ( function ( ) {
console. log ( 'gogogo' ) ;
} , 500 ) ;
function throttle ( fn, delay ) {
let flag = true ;
return function ( ) {
if ( flag) {
setTimeout ( ( ) => {
fn . call ( this )
flag = true ;
} , delay)
}
flag = false ;
}
}
< / script>