debounce与throttle区别





/** * 防反跳。func函数在最后一次调用时刻的wait毫秒之后执行! * @param func 执行函数 * @param wait 时间间隔 * @param immediate 为true,debounce会在wai 时间间隔的开始调用这个函数 * @returns {Function} */ function debounce(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = new Date().getTime() - timestamp; // timestamp会实时更新 if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = new Date().getTime(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; } /** * 创建并返回一个像节流阀一样的函数,当重复调用函数的时候,最多每隔 wait毫秒调用一次该函数 * @param func 执行函数 * @param wait 时间间隔 * @param options 如果你想禁用第一次首先执行的话,传递{leading: false}, * 如果你想禁用最后一次执行的话,传递{trailing: false} * @returns {Function} */ function throttle(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : new Date().getTime(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = new Date().getTime(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }

  

猜你喜欢

转载自www.cnblogs.com/ecmasea/p/8945939.html