1 防抖和节流函数
function debounce ( func, wait = 500 , immediate = true ) {
let timer = null ;
return function ( ... args) {
if ( timer) {
clearTimeout ( timer) ;
}
if ( immediate) {
if ( ! timer) {
typeof func === "function" && func . apply ( this , args) ;
}
timer = setTimeout ( ( ) => {
timer = null ;
} , wait) ;
} else {
timer = setTimeout ( ( ) => {
typeof func === "function" && func . apply ( this , args) ;
} , wait) ;
}
} ;
}
function throttle ( func, wait = 500 , immediate = true ) {
let isCanExecute = true ;
return function ( ... args) {
if ( immediate) {
if ( isCanExecute) {
isCanExecute = false ;
typeof func === "function" && func . apply ( this , args) ;
setTimeout ( ( ) => {
isCanExecute = true ;
} , wait) ;
}
} else {
if ( isCanExecute) {
isCanExecute = false ;
setTimeout ( ( ) => {
typeof func === "function" && func . apply ( this , args) ;
isCanExecute = true ;
} , wait) ;
}
}
} ;
}
2 Vue当中的写法
<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< meta http-equiv = " X-UA-Compatible" content = " ie=edge" />
< title> Vue</ title>
</ head>
< body>
< div id = " app" >
< button @click = " handleDebounceClick(1, 2)" > 按钮-防抖</ button>
< button @click = " handleThrottleClick(1, 2)" > 按钮-节流</ button>
</ div>
</ body>
< script src = " https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js" > </ script>
< script src = " ../utils.js" > </ script>
< script>
new Vue ( {
el : "#app" ,
data : {
num : 123 ,
} ,
methods : {
handleDebounceClick : debounce ( function ( data1, data2 ) {
console. log ( this . num) ;
console. log ( data1) ;
console. log ( data2) ;
} ) ,
handleThrottleClick : throttle ( function ( data1, data2 ) {
console. log ( this . num) ;
console. log ( data1) ;
console. log ( data2) ;
} ) ,
} ,
} ) ;
</ script>
</ html>
3 React当中的写法
import { debounce, throttle } from "../utils.js" ;
function Demo ( props ) {
const handleDebounceClick = debounce ( ( data1, data2 ) => {
console. log ( data1) ;
console. log ( data2) ;
} ) ;
const handleThrottleClick = throttle ( ( data1, data2 ) => {
console. log ( data1) ;
console. log ( data2) ;
} ) ;
return (
< React. Fragment>
< button onClick= { ( ) => handleDebounceClick ( 1 , 2 ) } > 按钮- 防抖< / button>
< button onClick= { ( ) => handleThrottleClick ( 1 , 2 ) } > 按钮- 节流< / button>
< / React. Fragment>
) ;
}