js防抖与节流
防抖:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="input">
<div id="text"></div>
<script>
const text = document.querySelector('#text');
const input = document.querySelector('#input');
function debounce(fn, delay) {
let timer = null;
return () => {
timer && clearTimeout(timer);
timer = setTimeout(fn.bind(this, arguments), delay);
}
};
function handleInput(arg) {
text.innerText = input.value;
console.log(arg);
};
input.addEventListener('input', debounce(handleInput.bind(this,'args'), 1000));
</script>
</body>
</html>
节流:
计时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="input">
<div id="text"></div>
<script>
const text = document.querySelector('#text');
const input = document.querySelector('#input');
function throttle(fn, delay) {
let timer = null;
return () => {
if(!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
};
function handleInput(arg) {
text.innerText = input.value;
console.log(arg);
};
input.addEventListener('input', throttle(handleInput.bind(this,'args'), 1000));
</script>
</body>
</html>
时间戳
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="input">
<div id="text"></div>
<script>
const text = document.querySelector('#text');
const input = document.querySelector('#input');
function throttle(fn, delay) {
let prev = Date.now(),
timer = null;
return () => {
let now = Date.now();
if(now - prev > delay) {
timer = setTimeout(() => {
fn.apply(this, arguments);
prev = Date.now();
}, delay);
}
}
};
function handleInput(arg) {
text.innerText = input.value;
console.log(arg);
};
input.addEventListener('input', throttle(handleInput.bind(this,'args'), 1000));
</script>
</body>
</html>