<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>防抖函数</title>
</head>
<body>
<script>
// function debounce(func, delay, immediate) {
// let time;
// return function () {
// let context = this;
// let args = arguments;
// clearTimeout(time);
// if (immediate) {
// let callNow = !time;
// time = setTimeout(() => {
// time = null;
// }, delay);
// if (callNow) {
// func.apply(context, args);
// }
// } else {
// time = setTimeout(function () {
// func.apply(context, args);
// }, delay);
// }
// };
// }
function debounce(func, delay, immediate) {
let timer, result;
let debounced = function () {
let context = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
}
if (immediate) {
let isExecute = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
if (isExecute) {
result = func.apply(context, args);
}
} else {
timer = setTimeout(function () {
func.apply(context, args);
}, delay);
}
return result;
};
debounced.cancel = function () {
clearTimeout(timer);
timer = null;
};
return debounced;
}
let count = 0;
let container = document.getElementById('#container');
let btn = document.querySelector('#btn');
function doSomeThing(e) {
console.log(e);
console.log(this);
container.innerHTML = count++;
return '想要的结果';
}
container.onmouseover = debounce(doSomeThing, 1000);
let doSome = debounce(doSomeThing, 1000);
btn.click = function () {
doSome.cancel();
};
let a = `scroll事件滚动触发;搜索框输入查询;表单验证;按钮的提交事件;浏览器的窗口缩放;`;
let b = `事件响应函数在一段时间后才执行,如果在这段时间内再次调用,则重新计算执行时间;当预定的时间内
没有再次调用,则执行相应逻辑;`;
</script>
</body>
</html>