/***
* @param fn {Function} 实际要执行的函数
* @param delay {Number} 延迟时间,也就是阈值,单位是毫秒(ms)
* * @return {Function} 返回一个“去弹跳”了的函数 */
function debounce(fn, delay) {var timer return function () { var that = this var arg = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(that, arg) } , delay) }}var div = document.getElementsByTagName('div')[0];div.style.width = '100px'div.style.height = '100px'div.style.background = "#f00"div.onmouseover = debounce(function () { console.log(111) }, 300)
/** * * @param fn {Function} 实际要执行的函数 * @param delay {Number} 执行间隔,单位是毫秒(ms) * * @return {Function} 返回一个“节流”函数 */
function debounce(fn, threshhold) { var timer var last threshhold || (threshhold = 250) return function () { var now = +new Date() var that = this var arg = arguments if (last && now < last + threshhold) { clearTimeout(timer) timer = setTimeout(function () { fn.apply(that, arg) } , threshhold) } else { fn.apply(that, arg) } last = now }}var div = document.getElementsByTagName('div')[0];div.style.width = '100px'div.style.height = '100px'div.style.background = "#f00"div.onmouseover = debounce(function () { console.log(111) }, 1000)
网友评论