防抖:事件被频繁触发,在规定的时间内一直触发函数,会重新计算时间,直到达到时间,函数才会执行最后一次
执行函数的最后一次代码
节流:事件被频繁的触发 每隔一段时间函数最多执行一次
目的:优化高频率发生事件 鼠标移动 滚动条 搜索框
lodash undescore
npm install lodash undescore -S
var _ = require('lodash');
input.oninput = _.debounce(function(){
xxxxx
},1000)
input.oninput = _.throttle(function(){
xxxxx
},1000)
防抖:
<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>
节流:
<style>
body{
height: 3000px;
}
</style>
<script>
window.onscroll = throttle(function(){
alert('我被调用了')
},2000)
function throttle(fun,wait){
// 定义一个变量控制定时器执行的频率
let id;
return function(){
if(!id){
id = setTimeout(function(){
fun();
// 为了持续等待wait事件执行定时器一次
id = null;
},wait);
}
// 限制事件执行频率
// t = false;
}
}
</script>