jQuery add and remove delay

懵懂的女人 提交于 2019-12-23 16:34:07

问题


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")


回答1:


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 →




回答2:


Without jQuery:

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


来源:https://stackoverflow.com/questions/5340053/jquery-add-and-remove-delay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!