Last active
January 19, 2016 08:04
-
-
Save zbinlin/f09ad2e41f2eea2d72c4 to your computer and use it in GitHub Desktop.
Debounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @param {Function} func | |
* 需要进行去抖的函数 | |
* @param {number} wait | |
* 去抖的时间间隔 | |
* @param {boolean} [lead = false] | |
* 是否要在开始执行 | |
* @returns {Function} | |
* 返回一个去抖函数 | |
*/ | |
function debounce(func, wait, lead) { | |
var tid, timestamp, | |
that, args; | |
function delayed(timeout) { | |
tid && clearTimeout(tid); | |
tid = setTimeout(function () { | |
handler(); | |
}, timeout); | |
} | |
function now() { | |
return Date.now ? Date.now() : new Date().getTime(); | |
} | |
function handler() { | |
return func.apply(that, args); | |
} | |
return function __debounced__() { | |
args = arguments; | |
that = this; | |
if (lead) { | |
if (!timestamp || (now() - timestamp) >= wait) { | |
handler(); | |
} | |
timestamp = now(); | |
} else { | |
delayed(wait); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment