1.0 防抖:所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间(应用场景:请求后台接口 如根据区域查询猪肉价格)
01.屏幕滑动事件中依次执行 代码如下:
//html 部分
<div id="content"></div>
//css 部分
<style>
*{
margin:0;
padding:0;
}
#content{
width:100vw;
height: 100vh;
border:0.025rem solid red;
background: gray;
font-size: 50px;
color:white;
text-align: center;
}
</style>
<script>
//防抖
function debounce(fn, delay) {
let timmer=null;
return function () {
let args = arguments;
clearTimeout(timmer);
timmer = setTimeout(() => {
fn.apply(this, args)
}, delay);
}
}
let num=1;
const content = document.getElementById('content');
function count (){
content.innerText =num++
}
content.onmousemove=debounce(count,1000)
</script>
效果: 滑动屏幕 1s中以后 页面显示num+1
2.节流:所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。(应用场景:上拉加载刷新 下拉加载更多) 代码如下:
//html 部分
<div id="content">这是一篇文档</div>
//css 部分
<style>
*{
margin:0;
padding:0;
}
#content{
width:100vw;
height: 100vh;
border:0.025rem solid red;
background: gray;
font-size: 50px;
color:white;
text-align: center;
}
</style>
<script>
//防抖
// throttle
const THRESHOLD = 50
function addMore(){
const offsetHeight = document.documentElement.offsetHeight;
const screenHeight = window.screen.height;
const scroolTop= window.scrollY;
const gap = offsetHeight-screenHeight-scroolTop;
if(gap > THRESHOLD){
console.log('加载……')
}else{
console.log('加载完成')
}
}
function throttle(method,delay){
var timer = null;
return function(){
var context = this, args=arguments;
clearTimeout(timer);
timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
window.onscroll= throttle(addMore,1000)
</script>
效果展示: 滑动屏幕完成 当gap>threshold 显示加载……反之显示加载完成 不会在滑动屏幕过程中显示加载 相当于不会多次请求接口加载下一页数据
参考文章:https://www.jianshu.com/p/c8b86b09daf0
网友评论