Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel setTimeout action after it has been triggered? [duplicate]

In my JavaScript I have some code that is executed when the page is loaded/reloaded. What it does is to click a hidden button so that 30 seconds after the page is loaded/reloaded, a pop-up window appears:

setTimeout(function() {
    $('#colorboxpopupform').click();
}, 30000);

The problem is that I also have another button that triggers that same pop-up window. This means that if someone loads/reloads the page and after 15 seconds clicks the button to load the pop-up window, the following code will make the same window to pop-up to be displayed again because the 30 seconds counter is still in process:

setTimeout(function() {
    $('#colorboxpopupform').click();
}, 30000);

What I need is that the code above opens the pop-up window after 30 seconds, only if I have not used my other button that triggers that same pop-up window. In other words, if the user explicitly clicks the button that triggers the pop-up window, I want for the code above to not trigger the pop-up window after 30 seconds anymore (cancel the action). How could I achieve that with JavaScript/jQuery? Thank you.

UPDATE 1:

I used the following solution, as Patrick P suggested in his answer, and it works:

if (localStorage.getItem("displaypopup") == "true") {
    var ticker = setTimeout(function() {
        $('#colorboxpopupform').click();
    }, 30000);
}
$("#headercolorboxpopupform").click(
    function() {
        clearTimeout(ticker);
    }
);
like image 495
Jaime Montoya Avatar asked Oct 27 '25 14:10

Jaime Montoya


1 Answers

Use clearTimeout() to cancel the timeout:

const ticker = setTimeout(function() {
    $('#colorboxpopupform').click();
}, 30000);

Call clearTimeout(ticker) when needed.

Documentation.

like image 170
Patrick Avatar answered Oct 30 '25 08:10

Patrick