Javascript function: It has been half a second since the last time you tried?

I would like to build a function that returns false if it was called less than 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 would like to avoid setTimeout () and ignore input if it is too fast to avoid overflow. Is this a good practice?

+3
source share
4 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 to (function() { ... })();create an anonymous function and run it immediately. timething.timechillthis function is not assigned. Instead, it is assigned the internal function returned by this function.

, lastCall ( var) . , lastCall , "" , .

timething.timechill , , . , - , ​​ .

, , lastCall , .

+5

, . , , " ". setTimeout - , . script.

+1

, , false, last . , .

:

timething.timechill = (function() {
    var last = 0;

    function timechill() {
        var now;

        now = new Date().getTime();
        if (last) {
            if (now - last > 500) {
                // It been long enough, allow it and reset
                last = now;
                return true;
            }
            // Not long enough
            return false;
        }

        // First call
        last = now;
        return false;
    }

    return timechill;
})());

timechill last. timechill, timething.timechill. , timechill, last, .

( , , , , , true, , , false.)

, . .:-) - SO " ", , , , .

0

"" , . ""!?

timething.timechill = function(){

    if (!timething._last_timechill){

       if ((new Date())-timething._last_timechill >= 500) return true;
       else return false;

    } else {

        timething._last_timechill = new Date();
        return false;

   }

}

You can replace "timething" with a "window" in a function if you want.

EDIT: As others have pointed out, you can also save the _last_timechill variable in closure.

0
source

Source: https://habr.com/ru/post/1741760/


All Articles