Created
June 10, 2012 12:19
-
-
Save ChillyBwoy/2905243 to your computer and use it in GitHub Desktop.
call function one per second
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
oneTimePer = (ms, func) -> | |
ms or (ms = 1000) | |
-> | |
self = arguments.callee | |
self._lastTimeCalled = new Date unless self.hasOwnProperty("_lastTimeCalled") | |
if new Date - self._lastTimeCalled > ms | |
self._lastTimeCalled = new Date | |
func.apply this, arguments | |
myFunc = oneTimePer 2000, (x, y) -> x + y | |
setInterval (-> | |
console.log myFunc(1, 2) | |
), 100 |
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 oneTimePer = function oneTimePer(ms, func) { | |
// 1 second by default | |
ms || (ms = 1000) | |
return function() { | |
var self = arguments.callee | |
if (!self.hasOwnProperty('_lastTimeCalled')) { | |
self._lastTimeCalled = new Date | |
} | |
if (new Date - self._lastTimeCalled > ms) { | |
self._lastTimeCalled = new Date | |
return func.apply(this, arguments) | |
} | |
} | |
} | |
// example: | |
var myFunc = oneTimePer(2000, function(x, y) { | |
return x + y | |
}) | |
setInterval(function() { | |
console.log(myFunc(1, 2)) | |
}, 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment