一、函数的防抖
现在有一个场景, 用户在输入框里面输入数据, 用户每输入一次数据, 方法都会往服务器请求一次. 这样对服务器的压力会非常大
模拟场景
鼠标移动, 修改数值
<!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>
<style>
.box {
width: 100%;
height: 300px;
background-color: black;
color: #fff;
line-height: 300px;
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<div class="box">
</div>
<script>
let count = 0
let box = document.querySelector(".box")
function doSomeThing() {
box.innerHTML = count++
}
box.onmousemove = doSomeThing
</script>
</body>
</html>
使用underscore库的debounce方法
_.debounce(要执行的函数, 多少秒后执行)
<script>
let count = 0
let box = document.querySelector(".box")
function doSomeThing() {
box.innerHTML = count++
}
box.onmousemove = _.debounce(doSomeThing, 1000)
</script>
二、手动封装函数的防抖
// 防抖函数, 第一个参数: 要执行的函数, 第二个参数: 等待的时间
function debounce(func, wait) {
let timeout;
return function() {
let context = this
// mouseEvent
let args = arguments
clearTimeout(timeout);
timeout = setTimeout(function(){
// 修改tis的指向
func.apply(context, args)
}, wait)
}
}
三、封装函数的节流
触发事件, 每隔一段时间, 只执行一次事件
<!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>
<style>
.box {
width: 100%;
height: 300px;
background-color: black;
color: #fff;
line-height: 300px;
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
function throttle(func, wait){
let context, args, timeout
return function() {
context = this
args = arguments
if(!timeout) {
timeout = setTimeout(()=>{
timeout = null
func.apply(context, args)
}, wait)
}
}
}
let count = 0
let box = document.querySelector(".box")
function doSomeThing(e) {
console.log(e);
box.innerHTML = count++
}
box.onmousemove = throttle(doSomeThing, 1000)
</script>
</body>
</html>