函数柯里化
function currying(){
let args=[...arguments]
let fn=function(){
args.push(...arguments)
return fn;
}
fn.toString=function(){
return args.reduce((pre,currt)=>{
return pre+currt;
})
}
return fn ;
}
console.log(currying(1)(1)(3,3).tostring());
console.log(currying(1)(1)(3,3)(2,2)(1,1,1).tostring());
防抖
<button id="button">点击事件<button>
function log(e){
console.log("触发事件log"+e)
}
function debounce(fn,delay){
let timer;
return function(){
let that=this;
let args=arguments;
clearTimeout(timer);
timer=setTimeout(()=>{
fn.apply(this,args);
},delay)
}
}
let logDebopunce=debounce(log,1000);
document.querySelector("#button").addEventListener("click",()=>{
logDebopunce("hhah")
})
节流
function setBackground(){
let r=Math.floor(Math.random()*255);
let g=Math.floor(Math.random()*255);
let b=Math.floor(Math.random()*255);
document.body.style.background=`rgb(${r},${g},${b})`
}
function throttle(func,delay){
let timer;
return function(){
let that=this;
let args=arguments;
if(timer){
return;
}
timer=setTimeout(function(){
func.apply(that,args)
timer=null;
},delay)
}
}
window.addEventListener("resize",throttle(setBackground,1000));