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

2019-08-11 09:39发布

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!

5条回答
倾城 Initia
2楼-- · 2019-08-11 10:17

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);
});
查看更多
We Are One
3楼-- · 2019-08-11 10:22

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);
});
查看更多
Viruses.
4楼-- · 2019-08-11 10:22

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-08-11 10:35
$('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/

查看更多
Lonely孤独者°
6楼-- · 2019-08-11 10:36

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);
查看更多
登录 后发表回答