<div id="content"
style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;">
</div>
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)
}
}
}
网友评论