防抖或是节流: 限制函数的执行次数
防抖: 通过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" /> <button value="btn">提交</button>
<script>
const inp = document.querySelector("input");
const btn = document.querySelector("button");
inp.oninput = debounce(get_value, 1000);
btn.onclick = debounce1(get_value, 1000);
function get_value() {
console.log(this.value);
}
// 防抖(多次触发事件之间,间隔delay秒后执行)
function debounce(fn, delay) {
let t = null;
return function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(() => {
fn.call(this);
}, delay);
};
}
// 防抖(先执行第一次,然后多次触发事件,执行delay秒间隔后的第一次)
function debounce1(fn, delay) {
let t = null;
return function () {
let firstClick = !t;
if (t) {
clearTimeout(t);
}
if (firstClick) {
fn.call(this);
}
t = setTimeout(() => {
t = null;
}, delay);
};
}
</script>
</body>
</html>
节流: 减少一段时间的触发频率
<!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" /> <button value="btn">提交</button>
<script>
const inp = document.querySelector("input");
const btn = document.querySelector("button");
btn.onclick = throttle(get_value, 1000);
function get_value() {
console.log(this.value);
}
// 节流
function throttle(fn, delay) {
var begin = 0;
return function () {
var current = new Date().getTime();
if (current - begin > delay) {
get_value.call(this);
begin = current;
}
};
}
</script>
</body>
</html>