我们用一副图来理解一下它的过程:
总结:防抖其实是延迟函数的执行
,只有当等待了一段时间也没有事件触发时,才会真正去执行函数
我们按照如下思路来实现:
<!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 id="cancel">取消</button>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
<!-- <script src="./01_debounce-v1-基本实现.js"></script> -->
<!-- <script src="./03_debounce-v3-立即执行.js"></script> -->
<!-- <script src="./04_debounce-v4-取消功能.js"></script> -->
<script src="./05_debounce-v5-函数返回值.js"></script>
<script>
const inputEl = document.querySelector("input")
let counter = 0
const inputChange = function(event) {
console.log(`发送了第${++counter}次网络请求`, this, event)
// 返回值
return "aaaaaaaaaaaa"
}
// 防抖处理
// inputEl.oninput = _.debounce(inputChange, 2000)
const debounceChange = debounce(inputChange, 3000, false, (res) => {
console.log("拿到真正执行函数的返回值:", res)
})
const tempCallback = (event) => {
debounceChange(event).then(res => {
console.log("Promise的返回值结果:", res)
})
}
inputEl.oninput = tempCallback
// 取消功能
const cancelBtn = document.querySelector("#cancel")
cancelBtn.onclick = function() {
debounceChange.cancel()
}
</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 id="cancel">取消</button>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
<!-- <script src="./06_throttle-v1-基本实现.js"></script> -->
<!-- <script src="./07_throttle-v1-leading实现.js"></script> -->
<!-- <script src="./08_throttle-v3-traling实现.js"></script> -->
<!-- <script src="./09_throttle-v4-this-参数.js"></script> -->
<!-- <script src="./10_throttle-v4-取消功能.js"></script> -->
<script src="./11_throttle-v6-函数返回值.js"></script>
<script>
const inputEl = document.querySelector("input")
let counter = 0
const inputChange = function(event) {
console.log(`发送了第${++counter}次网络请求`, this, event)
return 11111111111
}
// 节流处理
// inputEl.oninput = _.throttle(inputChange, 2000)
const _throttle = throttle(inputChange, 3000, {
leading: false,
trailing: true,
resultCallback: function(res) {
console.log("resultCallback:", res)
}
})
const tempCallback = (...args) => {
_throttle.apply(inputEl, args).then(res => {
console.log("Promise:", res)
})
}
inputEl.oninput = tempCallback
// 取消功能
const cancelBtn = document.querySelector("#cancel")
cancelBtn.onclick = function() {
_throttle.cancel()
}
</script>
</body>
</html>