首页 > Web开发 > 详细

js 防抖函数

时间:2017-12-15 23:18:51      阅读:261      评论:0      收藏:0      [点我收藏+]

第三个参数为是否取消延时

    function debounce (func, wait, immediate) {

      var timeout, result;

      var debounced =  function () {
        var context = this  // 找回this
        var arg = arguments // 找回event对象

        if (timeout) clearTimeout(timeout);

        if (immediate) {
          var callNow = !timeout;

          timeout = setTimeout(function () {
            timeout = false;
          }, wait)

          if (callNow) result = func.apply(context, arg);
        } else {
            timeout = setTimeout(function () {
            result = func.apply(context, arg)
          }, wait)
        }
        return result // 如果函数有返回值
      }

      // 第三个参数设置为true,在等待的时候
      // 我希望立即执行
      // 暴露出去
      debounced.cancel = function () {
        clearTimeout(timeout)
        timeout = false
      }
      return debounced
    }

js 防抖函数

原文:http://www.cnblogs.com/hmx99/p/8045102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!