防抖
<!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>
<div>
<button id="btn">添加记录</button>
<input type="text" name="" id="">
</div>
<script>
function addOne(args) {
console.log(this);
console.log(args);
console.log('添加一条记录');
}
function debounce(fun, time) {
let timer
return function(args) {
clearTimeout(timer)
timer = setTimeout(() => {
console.log(this);
console.log(args);
fun.call(this, args)
}, time)
}
}
function inputEvent(value) {
console.log(value);
}
const btn = document.getElementById('btn')
const options = {
name: '小明',
age: 18,
address: '广西桂林'
}
let debounceClick = debounce(addOne, 2000)
btn.addEventListener('click', function() {
debounceClick.call(this, options)
})
const input = document.querySelector('input')
let inputFn = debounce(inputEvent, 2000)
input.addEventListener('keyup', function(e) {
inputFn(e.target.value)
})
</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>节流</title>
</head>
<body>
<button id="btn">点击</button>
<script>
function thro(fun, wait) {
let timeout
return function() {
if (!timeout) {
timeout = setTimeout(() => {
fun()
timeout = null
}, wait)
}
}
}
function callBack() {
console.log('节流');
}
const btn = document.getElementById('btn')
btn.onclick = thro(callBack, 2000)
</script>
</body>
</html>