Search code examples
javascripttimeout

Stop timer JavaScript


I am trying to stop timer if div error div shows on page. Here is the code. I am not sure why clearTimeOut is not stopping timer.

    <script type="text/javascript">
        
        function timeOutRedirect(){
            
                var delay = 60000; // time in milliseconds

                // Show message div
                document.getElementById("message").style.display = "block";
                // Display message
                document.getElementById("message").innerHTML = "<h1>Your order is being processed.</h1>";

                setTimeout(function(){
                        if( document.getElementsByClassName('woocommerce-NoticeGroup-checkout').length != 0 ){
                        // If error div is loaded
                        delay = clearTimeout(); //this is n0t clearing timer
                        document.getElementById("message").style.display = "none";
                        console.log('error notice div loaded');
                    } else {
                        window.location = "/processing-information/";
                }
            },delay);

        }

    </script>
    <!-- Time out double order timer -->
    <div id="message" style="background: #a1f5b9; margin: 10px 0; padding: 10px; text-align: center; display: none; z-index: 99999;"></div>

Solution

  • If you have an interval, you can use the clearInterval() method.

    const handle = setInterval(function(){...},delay);
    ...
    // Cancel the interval
    clearInterval(handle)
    

    For a timer, you can use clearTimeout() method.

    const handle = setTimeout(function(){...},delay);
    ...
    // Cancel the timer
    clearTimeout(handle)
    

    See https://www.w3schools.com/jsref/met_win_cleartimeout.asp