1.0 防抖:所謂防抖佳鳖,就是指觸發(fā)事件后在 n 秒內(nèi)函數(shù)只能執(zhí)行一次脓匿,如果在 n 秒內(nèi)又觸發(fā)了事件,則會(huì)重新計(jì)算函數(shù)執(zhí)行時(shí)間(應(yīng)用場景:請求后臺接口 如根據(jù)區(qū)域查詢豬肉價(jià)格)
01.屏幕滑動(dòng)事件中依次執(zhí)行 代碼如下:
//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>
效果: 滑動(dòng)屏幕 1s中以后 頁面顯示num+1
2.節(jié)流:所謂節(jié)流考余,就是指連續(xù)觸發(fā)事件但是在 n 秒中只執(zhí)行一次函數(shù)杏死。節(jié)流會(huì)稀釋函數(shù)的執(zhí)行頻率。(應(yīng)用場景:上拉加載刷新 下拉加載更多) 代碼如下:
//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>
效果展示: 滑動(dòng)屏幕完成 當(dāng)gap>threshold 顯示加載……反之顯示加載完成 不會(huì)在滑動(dòng)屏幕過程中顯示加載 相當(dāng)于不會(huì)多次請求接口加載下一頁數(shù)據(jù)
參考文章:http://www.reibang.com/p/c8b86b09daf0