Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function: Has half a second passed since last time you tried?

I'd like to build a function that returns false if it's been called less that half a second ago.

timething.timechill=function(){
    var last
    if (last){
            if ((now.getTime()-last)>500){
                    return true
            }
            else{

                    return true
            }
    }
    else {
            last=now.getTime()
            return false
    }}

Any ideas? I'd like to avoid setTimeout() and ignore input if it's coming too quick to avoid overflow. Is this a good practice?

like image 690
heorling Avatar asked Oct 19 '25 05:10

heorling


1 Answers

timething.timechill = (function () {
    var lastCall = 0;
    return function () {
        if (new Date() - lastCall < 500)
            return false;
        lastCall = new Date();
        //do stuff
    }
})();

The idea here is that (function() { ... })(); will create an anonymous function and run it immediately. timething.timechill is not assigned this function. Instead, it is assigned the inner function returned by this function.

Note that lastCall is not declared (using the var keyword) within that inner function. And when the outer function returns, lastCall doesn't disappear because the inner function has "enclosed" it by virtue of the fact that it refers to the variable.

When you run timething.timechill later and it encounters this variable, it will search outside the function's scope for the variable and find the one that was declared earlier. When it returns, the variable still does not disappear, since it was declared outside the function's scope.

It is hard to explain this concept clearly, but it is very useful because lastCall is invisible to the rest of your code which doesn't need to see it.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!