标签:计时 line 时间间隔 ble head com out app hid
防抖是只在时间间隔wati内,不触发事件才执行。
原理: 设置一个定时器和最小间隔时间,如果用户触发在时间间隔内,就清空定时器,重新计时;否则在wait时间后执行函数。
分类: 防抖函数有两种,一种是第一次触发执行回调函数;一种是第一次触发不执行回调函数。
应用: 在某个动作(鼠标滚动,键盘输入)等结束后调用回调函数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content" style="height:850px;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 count() {
content.innerHTML = num++;
};
content.onmousemove = debounce(count, 2000, true);
function debounce(func, wait, immediate) { // 第三个参数表示第一次触发是否执行
let timer = null;
return function() {
const args = [].slice.call(arguments);
const _this = this;
if (timer) {
clearTimeout(timer);
}
if (immediate) {
let callNow = !timer;
if (callNow) { // 第一次
func.apply(_this, args);
}
}
timer = setTimeout(function() { // 回调函数可以改为箭头函数;就不需要将_this传入
func.apply(_this, args);
timer = null; // 下个周期的第一次
}, wait)
}
}
</script>
</body>
</html>
标签:计时 line 时间间隔 ble head com out app hid
原文地址:https://www.cnblogs.com/lyraLee/p/11465062.html