防抖

定义:对于短时间内连续触发得事件,防抖得意义就是让某个时间期限内,事件处理函数只执行一次

应用场景:

  1. scroll事件滚动触发
  2. 搜索框输入查询
  3. 表单验证
  4. 按钮提交事件
  5. 浏览器窗口缩放,reslize事件
    1. function debounce(func,wait){
    2. let timeout = null;
    3. return function(){
    4. let context = arguments;
    5. let _this = this;
    6. clearTimeout(timeout);
    7. timeout = setTimeout(function(){
    8. func.apply(_this,context)
    9. },wait)
    10. }
    11. }

    节流

    定义:如果你持续触发事件,每隔一段事件,只执行一次事件。

    1. function throttle(func,wait){
    2. let context,args
    3. let old = 0
    4. return function(){
    5. context = this
    6. args = arguments
    7. let now = new Date().valueOf()
    8. if (now - old>wait){
    9. func.apply(context,args)
    10. old = now
    11. }
    12. }
    13. }