throttle节流和debounce防抖

 

节流:

对于短时间内连续触发的事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效;

防抖:

对于短时间内连续触发的事件,让某个时间期限(如1000毫秒)内,事件处理函数只执行一次。

节流

指定时间间隔内只会执行一次函数

判断页面是否滚动到底部为例

function onScroll() {
    // 判断是否滚动到底部的逻辑
    const pageHeight = $('body').height();
    const scrollTop = $(window).scrollTop();
    const winHeight = $(window).height();
    const thresold = pageHeight - scrollTop - winHeight;

    if (thresold > -100 && thresold <= 20) {
        console.log('end');
    }
}

$(window).on('scroll', onScroll);

 在滚动时,每隔一段时间去计算这个判断逻辑。如果一直拖着滚动条进行滚动,那么会以1s的时间间隔,持续输出当前位置和顶部的距离

$(window).on('scroll', throttle(function () {
    // 判断是否滚动到底部的逻辑
    const pageHeight = $('body').height();
    const scrollTop = $(window).scrollTop();
    const winHeight = $(window).height();
    const thresold = pageHeight - scrollTop - winHeight;

    if (thresold > -100 && thresold <= 20) {
        console.log('end');
    }
}));
function throttle(fn, interval = 1000) {
    let canRun = true;
    return function () {
        if (!canRun) return;
        canRun = false;
        setTimeout(() => {
            fn.apply(this, arguments);
            canRun = true;
        }, interval);
    };
}


function throttle(fn,delay){
    let valid = true
    return function() {
       if(!valid){
           //休息时间 暂不接客
           return false 
       }
       // 工作时间,执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}
/* 请注意,节流函数并不止上面这种实现方案,
   例如可以完全不借助setTimeout,可以把状态位换成时间戳,然后利用时间戳差值是否大于指定间隔时间来做判定。
   也可以直接将setTimeout的返回的标记当做判断条件-判断当前定时器是否存在,如果存在表示还在冷却,并且在执行fn之后消除定时器表示激活,原理都一样
    */

// 以下照旧
function showTop  () {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  console.log('滚动条位置:' + scrollTop);
}
window.onscroll = throttle(showTop,1000) 

 

防抖:

函数频繁触发的情况下,只有函数触发的间隔超过指定间隔的时候,任务才会执行。

function debounce(fn,delay){
    let timer = null //借助闭包
    return function() {
        if(timer){
            clearTimeout(timer) 
        }
        timer = setTimeout(fn,delay) // 简化写法
    }
}
// 然后是旧代码
function showTop  () {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  console.log('滚动条位置:' + scrollTop);
}
window.onscroll = debounce(showTop,1000) // 为了方便观察效果我们取个大点的间断值,实际使用根据需要来配置

vue防抖

  <input v-model="inVal" placeholder="输入……">
<script>
const delay=(function(){
    let timer=0;
    return function(callback,ms){
        clearTimeout(timer)
        timer = setTimeout(callback,ms)
    }
})()
export default{
     watch: {
        inpVal: function (val, oldVal) {
          console.log('new: %s, old: %s', val, oldVal)
            delay(() =>{
               // 具体函数        
            },1000)
        }
    }
}
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端开发中,throttle节流)是一种优化性能的技术,用于限制函数的执行频率。它可以确保一个函数在一定时间间隔内只被执行一次。在给定的时间间隔内,如果多次触发了该函数,只有第一次触发会立即执行,后续的触发会被忽略,直到时间间隔过去后,再次触发时才会执行。这样可以减少函数的执行次数,避免资源的浪费和性能的下降。 在给出的引用中,有三个例子展示了throttle的实现方式。和是两种常见的方法,分别使用了时间戳和定时器来实现节流。其中,使用时间戳记录上次触发的时间,并通过与当前时间的差值判断是否满足时间间隔,如果满足则执行函数。使用定时器,在函数执行后设置一个定时器,当定时器触发时执行函数,如果在定时器触发前再次触发了函数,则清除之前的定时器重新设置。 另外,是一种防抖debounce)的例子,与节流类似,但是在时间间隔内的触发会重新计时,只有在一定时间内没有再次触发时才会执行函数。 需要注意的是,节流防抖都是根据实际需求来选择使用的,具体使用哪种方式要根据具体的场景和需求来确定。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [前端性能优化——节流throttle)](https://blog.csdn.net/weixin_43371610/article/details/100101268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [js 函数防抖debounce)函数节流throttle)](https://blog.csdn.net/qq_27009517/article/details/118381886)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值