/* 节流:一个函数执行一次后,只有大于设定的设定周期后才会执行第二次 */ /** * 节流函数 * @param fn 要被节流的函数 * @param delay 规定的时间 */ function throttle(fn, delay) { var lastTime = 0; return function () { var nowTime = new Date().getTime(); if (nowTime > lastTime + delay) { fn.call(this); lastTime = nowTime; } } } window.onscroll = throttle(function () { console.log('----' + new Date().getTime()) }, 200) /* 防抖:一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效*/ function debounce(fn, delay) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(function () { fn(); }, delay) } }