water_xcx/pages/index/tool.js

34 lines
1014 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*函数节流*/
function throttle(fn, interval) {
var enterTime = 0;//触发的时间
var gapTime = interval || 200 ;//间隔时间如果interval不传则默认200ms
return function() {
var context = this;
var backTime = new Date();//第一次函数return即触发的时间
if (backTime - enterTime > gapTime) {
fn.call(context,arguments);
enterTime = backTime;//赋值给第一次触发的时间,这样就保存了第二次触发的时间
}
};
}
/*函数防抖*/
function debounce(fn, interval) {
var timer;
var gapTime = interval || 1000;//间隔时间如果interval不传则默认1000ms
return function() {
clearTimeout(timer);
var context = this;
var args = arguments;
//保存此处的arguments因为setTimeout是全局的arguments不是防抖函数需要的。
timer = setTimeout(function() {
fn.call(context,args);
}, gapTime);
};
}
export default {
throttle,
debounce
};