首页 > 解决方案 > 停止计时器 JavaScript

问题描述

如果页面上显示 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>

标签: javascripttimeout

解决方案


如果你有一个间隔,你可以使用 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


推荐阅读