函數防抖和函數節流
阿新 • • 發佈:2018-07-13
imm urn amp art 執行 true UNC 開始 mouse
函數防抖(debounce)
????什麽是防抖?短時間內多次觸發同一個事件,只執行最後一次,或者只在開始時執行,中間不執行。
- 使用防抖之綠色基礎版
//綠色基礎版:
function debounce(doSomething,wait){
var timeout;//需要一個外部變量,為增強封裝,所以使用閉包
return function(){
var _this = this,
_arguments = arguments;//arguments中存著e
clearTimeout(timeout);
timeout = setTimeout(function(){
doSomething.apply(_this,_arguments);
},wait);
}
}
//觸發onmousemove事件
xcd.onmousemove = debounce(doSomething,1000);
- 使用防抖之立即執行版
//立即執行版
function debounce(doSomething,wait,isImmediate){
var timeout;
return function(){
var _this = this,
_arguments = arguments;
clearTimeout(timeout);
if(isImmediate){
var isTrigger = !timeout;
timeout = setTimeout(function(){
timeout = null;
}, wait)
isTrigger&&doSomething.apply(_this,_arguments);
}else{
timeout = setTimeout(function(){
doSomething.apply(_this,_arguments);
},wait);
}
}
}
//觸發onmousemove事件
xcd.onmousemove = debounce(doSomething,1000,true);
函數節流(throttle)
????什麽是節流?節流是連續觸發事件的過程中以一定時間間隔執行函數。節流會稀釋你的執行頻率,比如每間隔1秒鐘,只會執行一次函數,無論這1秒鐘內觸發了多少次事件。
- 使用節流之時間戳版
//綠色基礎版之時間戳版
function throttle(doSomething,wait){
var _this,
_arguments,
initTime = 0;
return function(){
var now = +new Date();//將new date()轉化為時間戳
_this = this;
_arguments = arguments;
if(now - initTime>wait){
doSomething.apply(_this,_arguments);
initTime = now;
}
}
}
//觸發onmousemove事件
xcd.onmousemove = throttle(doSomething,1000);
- 使用節流之定時器版
//綠色基礎版之定時器版
function throttle(doSomething,wait){
var timeout;
return function(){
var _this = this;
_arguments = arguments;
if(!timeout){
timeout = setTimeout(function(){
timeout = null;
doSomething.apply(_this,_arguments);
},wait);
};
}
}
//觸發onmousemove事件
xcd.onmousemove = throttle(doSomething,1000);
- 使用節流之雙劍合璧版
//節流之雙劍合璧版
function throttle(doSomething, wait) {
var timeout, _this, _arguments,
previous = 0;
var later = function() {
previous = +new Date();
timeout = null;
doSomething.apply(_this, _arguments)
};
var throttled = function() {
var now = +new Date();
//下次觸發 doSomething 剩余的時間
var remaining = wait - (now - previous),
_this = this;
_arguments = arguments;
// 如果沒有剩余的時間了
if (remaining <= 0) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
doSomething.apply(_this, _arguments);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
};
return throttled;
}
//觸發onmousemove事件
xcd.onmousemove = throttle(doSomething,1000);
函數防抖和函數節流