停止计时器Javacript

问题描述

如果页面显示div错误div,我正在尝试停止计时器。这是代码。我不确定为什么clearTimeOut没有停止计时器。

    <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>

解决方法

如果有间隔,则可以使用clearInterval()方法。

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

对于计时器,可以使用clearTimeout()方法。

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

请参见https://www.w3schools.com/jsref/met_win_cleartimeout.asp

,

也许您可以使用例如:

countTime = SetInterval(()=> console.log('Test'),1000); clearInterval(countTime);

这样,您可以操纵变量countTime在调用方法clearInterval时停止。