[SOLVED] Check if a button "hasn't" been clicked within a certain amount of time (jQuery)

Issue

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?

Solution

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

Answered By – Daniel van Dommele

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *