Check if a button “hasn't” been clicked within

2019-08-11 09:52发布

问题:

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!

回答1:

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);
});


回答2:

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


回答3:

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.



回答4:

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);
});


回答5:

$('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/