通过settimeout方式,在一定时间间隔内,将多次触发变成一次触发
<!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>Document</title>
</head>
<body>
<input type="text" name="" id="input" value="">
<input type="submit" id="button" />
</body>
<script>
let input = document.getElementById('input')
let button = document.getElementById('button')
button.addEventListener('click', debounce(submit, 1000), false);
function submit(e) {
// 请求操作
console.log('触发请求操作')
console.log(e)
console.log(this)
}
function debounce(fn, delay) {
let timerId = null;
return function () {
console.log(arguments[0])//获取事件对象
let e = arguments[0]
// 只要存在,清掉
if (timerId) {
clearTimeout(timerId)
}
// 重新声明,重新计时
timerId = setTimeout(() => {
fn.apply(this, e);//fn函数可以使用click时产生的事件对象
}, delay)
}
}
</script>
</html>