【问题标题】:Stop timer JavaScript停止计时器 JavaScript
【发布时间】:2020-08-24 19:43:20
【问题描述】:

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

【问题讨论】:

  • setTimeout 返回一个整数,应该在 clearTimeout 中传递
  • 你可以很容易地在谷歌上搜索到clearTimeout实际上是works的描述,这会清楚地告诉你为什么你的代码不起作用
  • 就像 Harmandeep 说的,你必须将一个整数参数(它标识要取消的具体超时)传递给clearTimeout
  • 嗨@Dave。欢迎来到堆栈溢出。在 Stack Overflow,人们重视提问者在提问之前做一些研究。例如,如果您在 Google 上搜索“cancel timer javascript”,您会发现对“clearInterval”的引用

标签: javascript timeout


【解决方案1】:

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

【讨论】:

  • 不是间隔,是超时。应该使用clearTimeout 吗? MDN 说它们可以互换使用,尽管他们建议使用各自的。
【解决方案2】:

也许你可以使用例如:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    相关资源
    最近更新 更多