// 函数防抖 function debounce(fn, wait) { var timeout = null; return function() { if (timeout !== null) clearTimeout(timeout); timeout = setTimeout(fn, wait); } }
// 函数节流 var throttle = function(func, delay) { var prev = Date.now(); return function() { var context = this; var args = arguments; var now = Date.now(); if (now - prev >= delay) { func.apply(context, args); prev = Date.now(); } } }
调用:
// 滚动事件 window.addEventListener('scroll', throttle(handle, 100));
// 滚动事件 window.addEventListener('scroll', debounce(handle, 100));
// 处理函数 function handle() { //相关操作 }