防抖(Debounce)和節(jié)流(throttle)都是用來控制某個(gè)函數(shù)在一定時(shí)間內(nèi)執(zhí)行多少次的技巧泌霍,兩者相似而又不同货抄。
防抖函數(shù)
防抖是指在一定時(shí)間內(nèi)只執(zhí)行一次事件,接下來我們看一下實(shí)例朱转。
function debouce(hanlder, wait) {
var t = null;
return function () {
clearTimeout(t);
t = setTimeout(hanlder, wait);
}
}
function hanlder() {
console.log('scroll~~~~');
}
window.addEventListener('scroll', debouce(hanlder, 500));
debouce.gif
節(jié)流函數(shù)
節(jié)流函數(shù)蟹地,只允許一個(gè)函數(shù)在規(guī)定的時(shí)間內(nèi)執(zhí)行一次。同樣藤为,我們現(xiàn)在來看一下實(shí)現(xiàn)方案:
var throttle = function (func, wait){
var timeout,
context,
args,
startTime = Date.parse(new Date());
return function(){
var curTime = Date.parse(new Date());
var remaining = wait - (curTime - startTime);
context = this;
args = arguments;
clearTimeout(timeout);
if(remaining <= 0){
func.apply(context, args);
startTime = Date.parse(new Date());
}else{
timeout = setTimeout(func, remaining);
}
}
};
柯里化函數(shù)
function curry(fn) {
let args = [];
return function result(...rest) {
if (rest.length === 0) {
return fn(args);
}
args.push(...rest);
return result;
}
}