David Horák
David Horák

Reputation: 5565

jQuery add and remove delay

how a can get this, in jQuery: call some function with working code after delay(3s), IF i call function again before delay from first call in not done, then reset delay and call new 3s.

Example:

fce MeDeday(3s) - after time down - alert("hello");

situation 1:

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

situation 2:

call MeDelay()

still remain 2s from first call

reset time and again wait 3s, no 2s + 5s and fired 2times alert("hello")

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

Upvotes: 3

Views: 2331

Answers (2)

Matt Ball
Matt Ball

Reputation: 359966

This is called debouncing, which is closely related to throttling. There's a nice jQuery plugin for that: jQuery throttle/debounce.

I think this is the use case you're looking for:

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

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

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

Demo →

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816810

Without jQuery:

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

Upvotes: 4

Related Questions