简体   繁体   English

使用jQuery stop()暂停超时功能

[英]pause timeoutfunction with jQuery stop()

I have two buttons. 我有两个按钮。 The first one lets appear an alert with a delay of 3 seconds and another one 3 seconds later. 第一个让我们出现一个延迟3秒的警报,另一个让3秒后出现。 The second button must be able to pause the setTimeout function. 第二个按钮必须能够暂停setTimeout函数。

So when the first alert has appeared and I click on 'pause' the second should not show up. 因此,当第一个警报出现并且我单击“暂停”时,第二个警报应该不会显示。 I know I'm close to the solution, but it still doesn't work. 我知道我已经接近解决方案,但是仍然无法正常工作。 My code is: 我的代码是:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#start").click(function () {
                setTimeout(myFunction, 3000);
                setTimeout(myFunction, 6000);
            });
            $("#stop").click(function () {
                $("myFunction").stop();
            });
        });

        function myFunction() {
            alert('Hello');
        }
    </script>
</head>
<body>
    <p>
        <button id="start">Start</button>
        <button id="stop">Pause</button>
    </p>
</body>
</html>

To achieve this you need to store a reference to your setTimeout() calls and then call clearTimeout() on them when needed. 为此,您需要存储对setTimeout()调用的引用,然后在需要时在它们上调用clearTimeout() Try this: 尝试这个:

$(document).ready(function() {
    var timers = [];

    $("#start").click(function(){
        timers.push(setTimeout(myFunction, 3000));
        timers.push(setTimeout(myFunction, 6000));
    });

    $("#stop").click(function(){
        timers.forEach(function(timer) {
            clearTimeout(timer);
        });
    });
});

function myFunction() {
    console.log('Hello'); // note: use console.log to debug, especially with async/blocking functions
}

The best way to do this is to check with cookies. 最好的方法是检查Cookie。

This is how I would do this: 这就是我要这样做的方式:

1. Before starting alert check if there is a cookie named for example "some_cookie" and it's value;
2. When you click on "pause" it stores value "1" in to "some_cookie";
3. If value is "0" than run;

Easy. 简单。 just busy to write you code. 只是忙着为您编写代码。 If you need it, just tell me. 如果需要,请告诉我。 I'll write. 我会写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM