點擊查看 源碼
var debounce = function (fn, delay, isImmediate) { var timer = null; // 默認不當即觸發 isImmediate = typeof isImmediate === "undefined" ? false : isImmediate; return function () { var ctx = this, // 保存做用域 args = arguments; // 保存參數 // 初始化清空全部定時器 if (timer) { clearTimeout(timer); } // 若是是當即觸發 if (isImmediate) { if (!timer) { // timer爲空時觸發操做 fn.apply(ctx, args); } // delay時間後置空timer timer = setTimeout(_ => { timer = null; }, delay); } else { // delay時間後觸發操做 timer = setTimeout(_ => { fn.apply(ctx, args); }, delay); } }; };
防抖動當即觸發git
防抖動github
var throttle = function (fn, delay, isImmediate) { var timer = null; // 默認當即觸發 isImmediate = typeof isImmediate === "undefined" ? true : isImmediate; return function () { var ctx = this, // 保存做用域 args = arguments; // 保存參數 if (!timer) { // timer爲空時 if (isImmediate) fn.apply(ctx, args); // 當即觸發 timer = setTimeout(function () { clearTimeout(timer); timer = null; if (!isImmediate) fn.apply(ctx, args); // delay時間後觸發操做 }, delay); } }; };
節流當即觸發
節流app