Created
August 13, 2015 12:34
-
-
Save larryprice/f83ef2ec4e7a5dd8c020 to your computer and use it in GitHub Desktop.
mimicing _.throttle
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
var _ = {}; | |
_.throttle = function (func, wait, options) { | |
var initial; | |
return function () { | |
if (!initial || new Date() - initial >= wait) { | |
initial = new Date(); | |
func.apply(this, arguments); | |
} | |
}; | |
} | |
var f = function (s) { | |
console.log(s); | |
} | |
var throttledF = _.throttle(f, 10); | |
var i = 1; | |
throttledF(i++); // 1 | |
throttledF(i++); | |
throttledF(i++); | |
setTimeout(function () { | |
throttledF(i++); // 4 | |
throttledF(i++); | |
throttledF(i++); | |
}, 5); | |
setTimeout(function () { | |
throttledF(i++); | |
throttledF(i++); | |
throttledF(i++); | |
}, 10); | |
setTimeout(function () { | |
throttledF(i++); // 10 | |
throttledF(i++); | |
throttledF(i++); | |
}, 15); | |
setTimeout(function () { | |
throttledF(i++); // 13 | |
throttledF(i++); | |
throttledF(i++); | |
}, 20); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment