jQuery倒计时暂停并重复

时间:2011-04-12 09:43:00

标签: jquery mouseevent counter keyboard-events

我正在尝试将某些功能编码到页面,但我无法整理所有部分: - (

我想要的只是简单的计数器,它计数为0,然后显示消息(.confirmation)。如果您中断(移动鼠标或触摸keyobaord)计数器暂停并显示不同的消息(.warning),并在几秒钟后从开始重复计数。 UFFF ...

我有用于监控用户操作和控制器的元素,但我不知道如何将它们添加到一起:

       //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            $('.warning').show().delay(2000).fadeOut(500);
        }); 

        //counts for example from 5 seconds (this value is in the <span></span> in html section) 
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);

1 个答案:

答案 0 :(得分:1)

尝试类似的东西:

        //countdown pause timer
        var countDownPauseTimer = 0;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        }); 

        //counts for example from 5 seconds (this value is in the <span></span> in html section) 
        var sec = $('#box span').text()
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);

我在这里做的是引入另一个变量来表示我们正在暂停倒计时并保持暂停的秒数。

在间隔时间内,我检查是否有暂停并决定减少哪个值...

我没有测试它,但它应该可以工作。

更新

以下是暂停结束后重新开始倒计时的更新代码:

        //countdown pause timer
        var countDownPauseTimer = -1;

        //monitors user action
        $('.warning, .confirmation').hide();

        $(document).bind('mousemove keydown', function() {
            countDownPauseTimer = 10; // Countdown will pause for 10 seconds
            $('.warning').show().delay(2000).fadeOut(500);
        }); 

        //counts for example from 5 seconds (this value is in the <span></span> in html section) 
        var sec = $('#box span').text();
        var timer = setInterval(function() {
           if (countDownPauseTimer > 0)
                countDownPauseTimer--;
           else if (countDownPauseTimer == 0) {
                countDownPauseTimer--;
                sec = $('#box span').text();
           }
           else
                $('#box span').text(--sec);
           if (sec == 0) {
              $('.confirmation').show(function() {
                $(document).unbind();
              });
              clearInterval(timer);
           }
        }, 1000);