//防抖(立即执行)functiondebounce_2(fn,wait){let timerId =null;let flag =true;returnfunction(){clearTimeout(timerId);if(flag){
fn.apply(this,arguments);
flag =false}
timerId =setTimeout(()=>{ flag =true},wait)}}
1.3 合并版
//防抖(合并版)functiondebounce_merge(fn,wait =500,isImmediate =false){let timerId =null;let flag =true;if(isImmediate){returnfunction(){clearTimeout(timerId);if(flag){
fn.apply(this,arguments);
flag =false}
timerId =setTimeout(()=>{ flag =true},wait)}}returnfunction(){clearTimeout(timerId);
timerId =setTimeout(()=>{
fn.apply(this,arguments)},wait)}}
//定义函数//节流(非立即执行)functionthrottle_1(fn,wait){let flag =true;returnfunction(){if(flag ==true){
flag =falsevar timer =setTimeout(()=>{
fn.apply(this,arguments)
flag =true},wait)}}}
2.2 立即执行版
//节流(立即执行)functionthrottle_2(fn,wait){var flag =true;var timer =null;returnfunction(){if(flag){
fn.apply(this,arguments);
flag =false;
timer =setTimeout(()=>{
flag =true},wait)}}}
2.3 合并版
//节流(合并)functionthrottle_merge(fn,wait =500,isImmediate =false){let flag =true;let timer =null;if(isImmediate){returnfunction(){if(flag){
fn.apply(this,arguments);
flag =false;
timer =setTimeout(()=>{
flag =true},wait)}}}returnfunction(){if(flag ==true){
flag =falsevar timer =setTimeout(()=>{
fn.apply(this,arguments)
flag =true},wait)}}}
2.4 合并版 + 立即取消等待
//节流(合并)exportconstthrottle=function(fn, wait =500, isImmediate =false){let flag =true;let timer =null;let resultFunc =null;if(isImmediate){// 立即执行resultFunc=function(){if(flag){
fn.apply(this, arguments);
flag =false;
timer =setTimeout(()=>{
flag =true}, wait)}}
resultFunc.cancel=function(){
console.log("立即取消等待")clearTimeout(timer)}}else{// 不立即执行resultFunc=function(){if(flag ==true){
flag =false
timer =setTimeout(()=>{
fn.apply(this, arguments)
flag =true}, wait)}}
resultFunc.cancel=function(){
console.log("立即取消等待")clearTimeout(timer);
flag =true;}}return resultFunc;}