开发者

jQuery add and remove delay

开发者 https://www.devze.com 2023-02-17 22:58 出处:网络
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.

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:

ca开发者_开发问答ll 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")


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 →


Without jQuery:

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

精彩评论

暂无评论...
验证码 换一张
取 消