Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Created June 10, 2012 12:19
Show Gist options
  • Save ChillyBwoy/2905243 to your computer and use it in GitHub Desktop.
Save ChillyBwoy/2905243 to your computer and use it in GitHub Desktop.
call function one per second
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
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