undescore lodash debounce throttle
一、防抖
防抖:在一定时间内再次触发该函数,则会重新计算时间,超过预定时间,则会执行最后一次函数(事件被频繁触发,在规定的时间内一直触发函数,会重新计算时间,直到达到时间,函数才会执行最后一次)
目的:优化高频率事件触发得手段
<!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>
<script>
window.onload = function(){
var input = document.querySelector('input');
input.oninput = debounce(function(){
console.log(this.value)
},1000);
function debounce(fun,wait){
let timer = null;
return function(){
// console.log(this.value,'获取输入框的值')
if(timer!=null){
clearTimeout(timer)
}
var that = this;
timer = setTimeout(function(){
fun.call(that)
},wait)
}
}
}
</script>
</head>
<body>
<input type="text">
</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>
<style>
body{
height: 3000px;
}
</style>
<script>
window.onscroll = throttle(function(){
alert('我被调用了')
},2000)
function throttle(fun,wait){
// 定义一个变量控制定时器执行的频率
// let t = true;
let id;
return function(){
if(!id){
id = setTimeout(function(){
fun();
// t=true;
// 为了持续等待wait事件执行定时器一次
id = null;
},wait);
}
// 限制事件执行频率
// t = false;
}
}
</script>
</head>
<body>
</body>
</html>