防抖与节流

let num = 1; let content = document.getElementById('content'); function count() { content.innerHTML = num++; }; content.onmousemove = throttle2(count, 500); //防抖非立即执行版本: function debounce1(fun, wait) { let t; return function () { let context = this, args = arguments; t ? clearTimeout(t) : undefined; t = setTimeout(() => { fun.apply(context, args); }, wait); } } //防抖立即执行版本 function debounce2(fun, wait) { let t; return function () { let context = this, args = arguments; t ? clearTimeout(t) : undefined; let callNow = !t; t = setTimeout(() => { t = null; }, wait) if (callNow) fun.apply(context, args) } } //节流时间戳版本 function throttle1(fun, wait) { let last = 0; return function () { let context = this, args = arguments; et now = Date.now(); if (now - last > wait) { fun.apply(context, args); last = now; } } } //节流定时器版本 function throttle2(fun, wait) { let t; return function () { let context = this, args = arguments; if (!t) { t = setTimeout(() => { t = null; fun.apply(context, args); }, wait) } } }

你可能感兴趣的:(防抖与节流)