part1 防抖
<!DOCTYPE html>
<html>
<!-- 防抖 -->
<!-- 防抖就是在n秒内 防止连续触发,在n秒内触发了下一次,那就重新计算 -->
<body>
<div id="content"
style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
<script>
let num = 1;
let content = document.getElementById('content');
/**
*非立即执行版
**/
function debounceNoAtOnce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
};
/**
*立即执行版
**/
function debounceAtOnce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
debugger
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
}
/**
*聚合版
**/
function debounce(func, wait, immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
} else {
timeout = setTimeout(function () {
func.apply(context, args)
}, wait);
}
}
}
function count() {
content.innerHTML = num++;
};
content.onmousemove = debounce(count, 1000, true);
</script>
</body>
<script>
</script>
</html>
防抖的目的在于:n秒内点击多少次都算一次+每次点击都重新计算时间
应用场景:地图点击
part2 节流
<!DOCTYPE html>
<html>
<!-- 节流 -->
<!-- 节流是为了固定的时间段内只能点击一次 -->
<body>
<div id="content"
style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
<script>
let num = 1;
let content = document.getElementById('content');
/**
*throttleTime 时间戳版
**/
throttleTime = function (func, wait) {
let previde = 0;
return function () {
let nowDate = Date.now();
if (nowDate - previde > wait) {
func();
previde = nowDate;
}
}
}
/**
*throttleSet 定时器版
**/
throttleSet = function (func, wait) {
let timeout;
return function () {
if (!timeout) {
timeout = setTimeout(() => {
timeout = false
func()
}, wait)
}
}
}
function count() {
content.innerHTML = num++;
};
content.onmousemove = throttleSet(count, 1000);
</script>
</body>
<script>
</script>
</html>
节流的目的在于:固定时间段内只能点击一次
应用场景:输入框输入+提交/确定