Created
August 21, 2013 09:01
-
-
Save 6174/6292036 to your computer and use it in GitHub Desktop.
throttle 函数啦 *_*
This file contains hidden or 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
/** | |
* 版本1 | |
* Throttles a call to a method based on the time between calls. | |
* @param {Function} fn The function call to throttle. | |
* @param {Object} [context] context fn to run | |
* @param {Number} [ms] The number of milliseconds to throttle the method call. | |
* Passing a -1 will disable the throttle. Defaults to 150. | |
* @return {Function} Returns a wrapped function that calls fn throttled. | |
* @member KISSY | |
*/ | |
function throttle(fn, ms, context) { | |
ms = ms || 150; | |
if (ms === -1) { | |
return (function () { | |
fn.apply(context || this, arguments); | |
}); | |
} | |
var last = +new Date(); | |
return (function () { | |
var now = +new Date(); | |
if (now - last > ms) { | |
last = now; | |
fn.apply(context || this, arguments); | |
} | |
}); | |
} | |
This file contains hidden or 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
var now = require('../time/now'); | |
/** | |
*/ | |
function throttle(fn, delay){ | |
var context, timeout, result, args, | |
cur, diff, prev = 0; | |
function delayed(){ | |
prev = now(); | |
timeout = null; | |
result = fn.apply(context, args); | |
} | |
function throttled(){ | |
context = this; | |
args = arguments; | |
cur = now(); | |
diff = delay - (cur - prev); | |
if (diff <= 0) { | |
clearTimeout(timeout); | |
prev = cur; | |
result = fn.apply(context, args); | |
} else if (! timeout) { | |
timeout = setTimeout(delayed, diff); | |
} | |
return result; | |
} | |
return throttled; | |
} | |
module.exports = throttle; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment