<!document>
<html>
<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>Document</title>
<style></style>
</head>
<body>
<button id="save">提交/保存</button>
<input type="text" placeholder="请输入" id="search"/>
</body>
<script>
// 防抖 概述:当持续触发事件时,保证只执行最后一次事件的处理函数
// 应用场景:onchang oninput 搜索功能等
function debounce(fn){
let timer = null;
return function () {
// 如果定时器存在,就清除掉
if (timer) {
clearTimeout(timer);
}
console.log('debounce==', this)
// 否则就创建新的定时器
// .bind(this)将timer的this改变成当前事件的this
timer = setTimeout(function(){
// 需要执行的方法
console.log('debounce setTimeout==', this)
// 将fn的this改变成input的this
fn.call(this);
}.bind(this), 500)
}
}
// 节流 概述:当持续触发事件时,保证一段时间内执行一次事件处理函数
// 应用场景:加载更多 屏幕滚动 高频点击提交按钮等
function throttle(fn){
let flag = true;
if (!flag) {
return;
}
flag = false;
return function(){
setTimeout(function(){
fn();
flag = true;
}, 500)
}
}
document.getElementById('search').addEventListener('input', debounce(function(){
console.log('debounce callback==', this)
console.log(this.value)
}))
document.getElementById('save').addEventListener('click', throttle(function(){
console.log('throttle callback==', this)
}))
</script>
</html>