JQuery add and remove delay

how can this be obtained in jQuery: call some function with working code after the delay (3s), IF I call the function again before the delay from the first call, and then reset delay and call the new 3s.

Example:

fce MeDeday (3s) - after exiting the standby mode ("hello");

situation 1:

call MeDelay () - time down - warning ("hello")

situation 2:

call MeDelay ()

still 2 from the first call

reset again and again wait for 3s, no 2s + 5s and activate the warning 2times ("hello")

call MeDelay () - time down - warning ("hello")

+3
source share
2 answers

debouncing,, . jQuery : jQuery throttle/debounce.

, , :

function fn()
{
    alert('hello');
}

var debouncedFn = $.debounce(3000, fn);

$('#my-button').click(debouncedFn);

Demo β†’

+4

jQuery:

var MeDelay = (function() {
    var timer;
    return function(timeout) {
        timeout = timeout || 3000;
        if(timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function() {
            alert('hello');
        }, timeout);
    }
}());
+4

All Articles