• JS 函数节流与防抖


    函数节流:一个函数执行一次后,只有大于设定的周期才执行第二次,可以理解为指定时间间隔内只会执行一次任务

    函数节流所做的工作就是每隔一段时间去执行一次原本需要无时不刻地在执行的函数

    fn---函数
    time---变量
    function throttle(fn,timegap){
    let initTime=0;
    return function(){
    let nowTime=Date.now();
    if(nowTime-initTime>timegap){
    fn.call(this)
    initTime=nowTime
    }
    }
    }
    //调用 document.body.onscroll=throttle(function(){ console.log('触发了onscroll'+Date.now())},1000)

    函数防抖: 一个需要频繁执行的函数,在规定时间内,只让最后一次生效,前面的不生效,任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行

    通过闭包保存一个标记来保存setTimeout返回的值,每当函数执行的时候把前一个setTimeoutclear 掉,然后又创建一个新的setTimeout,这样就能保证执行函数后的timegap间隔内如果还有触发函数,就不会执行fn函数了

    function debounce(fn,timegap){
    let timer=null;
    return function(){
      clearTimeout(timer);
    timer=setTimeout(function(){
      fn.call(this);  
    },timegap)
    }
    }
    
    //调用
    document.body.onclick=debounce(function(){console.log('点击了body'+Date.now())},2000)
  • 相关阅读:
    119. Pascal's Triangle II
    118. Pascal's Triangle
    112. Path Sum
    111. Minimum Depth of Binary Tree
    110. Balanced Binary Tree
    108. Convert Sorted Array to Binary Search Tree
    88. Merge Sorted Array
    83. Remove Duplicates from Sorted List
    70. Climbing Stairs
    陌陌面试经历
  • 原文地址:https://www.cnblogs.com/chandlerwong/p/14651061.html
Copyright © 2020-2023  润新知