点击查看 源码
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