防抖函数
能够用防抖debounce等优化形式,缩小http申请;
这里以滚动条事件举例:防抖函数 onscroll 完结时触发一次,提早执行
function debounce(fun,wait){ let timeout return function(){ let content = this let args = arguments if(timeout){ clearTimeout(timeout) } timeout = setTimeout(()=>{ fun.apply(content,args) },wait) } } window.onscroll = debounce(function(){ console.log('我就执行一次') },5000)
节流函数
只容许一个函数在N秒内执行一次。滚动条调用接口时,能够用节流throttle等优化形式,缩小http申请;
function throttle(fn, delay) { let prevTime = Date.now(); return function() { let curTime = Date.now(); if (curTime - prevTime > delay) { fn.apply(this, arguments); prevTime = curTime; } };}// 应用var throtteScroll = throttle(function() { console.log('我就执行一次')}, 1000);window.onscroll = throtteScroll;