RE: Javascript Timeout, on click cancel. [SOLVED]

Hey so for a project I am working on, I have a link that opens a modal that informs the user the url is about to redirect, they can either click to continue, or allow the timer to run down (in which case it redirects) or click to stay on the page. (there is a countdown also displayed in the modal).

The code I am using works perfect for the countdown and redirect, I am just not sure how to cancel the timeout if the user selects to stay on the page.

My guess at this stage is my script needs a different approach maybe?

<script>
    var seconds = 15;
    
    function goRedirect() {
        seconds = seconds - 1;
        if (seconds < 0) {
            // Redirect Link
            window.location = "https://www.domain.com";
        } else {
          
            // Update seconds
            document.getElementById("countdown").innerHTML = seconds;

            window.setTimeout("goRedirect()", 1000);
        }
    }
</script>
1 Like

Something like:

function myStopFunction() {
  clearTimeout(myVar);
}

And that’s before :coffee: :upside_down_face:

2 Likes

+1 This is how I’d do it.

2 Likes

Sweet, thanks guys.

Just incase anyone is interested this is it…

<script>
  var seconds = 15;
    
    function goRedirect() {
        seconds = seconds - 1;
        if (seconds < 0) {
            // Redirect Link
            window.location = "https://www.domain.com";
        } else {
          
            // Update seconds
            document.getElementById("countdown").innerHTML = seconds;

            redirectTimer  = window.setTimeout("goRedirect()", 1000);
        }
    }

 function stopRedirect() {
    // Stop Timer
     clearTimeout(redirectTimer);
   // Reset seconds
   seconds = 15;
}

</script>

My stop button has 2 attributes

onclick="stopRedirect()"

and

data-dismiss="modal"

(The second one closes the modal).

3 Likes

UPDATE: So I realised because I was using a Modal, it’s possible to click out side the modal to dismiss it. This means the countdown is still running in the background and the page eventually redirects, surprising the user.

A better approach is to use a Modal event “hidden.bs.modal” for when the Modal is dismissed.

So I replaced the stopRedirect function with…

$('#myModalID').on('hidden.bs.modal', function (event) {
  clearTimeout(redirectTimer);
  seconds = 30;
})

Could this be used for a Pop Up window (Call To Action)
or what if the user is about to exit or move off the page?

@KBConcepts, pretty sure you already had a thread with a popup window a while back?

But in my case this is what it looks like (well an early draft does anyway)…

A user clicks a link, the modal pops up, the countdown begins, when it reaches 0 seconds it redirects. The user can either cancel or redirect straight away.