防抖(多少毫秒之内调用一次,减少代码调用次数,提高性能)
常用于onmousemove,onresize,oninput,onscroll
function debuce ( fn, delay) {
let timeId= null ;
return function ( ) {
let self= this ;
let args= arguments;
timeId&& clearTimeout ( timeId) ;
timeId= setTimeout ( function ( ) {
fn. apply ( self, args) ;
} , delay|| 1000 )
}
}
function test ( event) {
console. log ( this , event)
}
document. getElementById ( 'int' ) . oninput= debuce ( test, 2000 ) ;
节流(多少毫秒之内调用多次,减少代码调用次数,提高性能)
function throttle ( fn, delay) {
let timeId= null ;
let flag= true ;
return function ( ) {
if ( ! flag) {
return
}
let self= this ;
let args= arguments;
flag= false ;
timeId&& clearTimeout ( timeId) ;
timeId= setTimeout ( function ( ) {
flag= true ;
fn. apply ( self, args) ;
} , delay|| 500 )
}
}
function test ( event) {
console. log ( this , event)
}
document. getElementById ( 'int' ) . oninput= throttle ( test, 1000 ) ;