简体   繁体   中英

Check if a button “hasn't” been clicked within a certain amount of time (jQuery)

Basically:

You click a button and it runs function 1.
If you don't click the button again within 1 second then function 2 runs.
If you click the button within 1 second then it runs function 1 again.
and so on and so forth...

I can't figure out the logic to do this in Javascript.

Is there even a way?

Thanks in advanced!

You'll want to use a timer to keep track of the time. You can use setTimeout to run function 2 in 1 second (1000ms). If, however, you click button again, you should stop the timer. You can do that using clearTimeout .

The core lines would be:

var timer;

// in button's click handler:
clearTimeout(timer);
timer = setTimeout(function2, 1000);

from the top of my head (haven't tested this, but this seems most logic to me):

var t = null;

$("button").click(function() {
    console.log("this is function 1");
    if (t !== null) { window.clearTimeout(t); }

    t = window.setTimeout(function() {
        console.log("and this is function 2");
    }, 1000);
});

This should do it:

(function() {
    var timer = null;

    $('#button').on('click', function() {
        function1();                         // always call function1
        clearTimeout(timer);                 // clear the timer
        timer = setTimeout(function2, 1000); // run function2 1s later
    });
})();

See http://jsfiddle.net/alnitak/QZRTA/

The outer function block serves to keep the timer variable in the local scope without creating a global variable.

Using setTimeout and clearTimeout :

var t = null;
var timeoutMs = 1000; // in ms

$("#btn1").click(function (){
    func1();
    if (t !== null)
        clearTimeout(t);    
    t = setTimeout(func2, timeoutMs);
});
$('button').click(function() {
    console.log('Func 1');
    clearTimeout($(this).data('throttle'));
    $(this).data('throttle', setTimeout(function() {
        console.log('Func 2');
    }, 1000));
});​

http://jsfiddle.net/dfsq/rrXWt/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM