Your function as defined will always return false
because the last
variable is never saved anywhere. You could hold it as a property of an object, or you can hold it within a closure.
Here's a closure example:
timething.timechill = (function() {
var last = 0;
function timechill() {
var now;
now = new Date().getTime();
if (last) {
if (now - last > 500) {
// It's been long enough, allow it and reset
last = now;
return true;
}
// Not long enough
return false;
}
// First call
last = now;
return false;
}
return timechill;
})());
That uses an anonymous scoping function to build your timechill
function as a closure over the last
variable. The anonymous scoping function returns a reference to the timechill
function, which gets assigned to timething.timechill
. Nothing other than the timechill
function can access last
, it's entirely private.
(I'm sure the actual logic of the function could be refactored a bit, but I think that's pretty close to your original except there was one place you were returning true
where I think you wanted false
.)
Whether this is a good idea depends entirely on your use-case. I wouldn't busy-loop on the above. :-) But if you're using it to pop up something like SO's "You can only rate a comment once every five seconds" things, it would be fine, although in that case I'd probably generalize it.