选项卡处于非活动状态或最小化浏览器时的计时器延迟

时间:2018-11-04 18:24:21

标签: javascript php timer setinterval form-submit

我有以下代码显示在线测验应用程序的计时器。完成后,我需要通过ajax重定向到另一个页面。 该代码对我有用,但是我发现当我们移动制表符或最小化浏览器时,计时器会延迟。

          var mins = 5;
          var secs = 0; // Seconds (In addition to min) test time
          var timerDisplay = $(document).find('#timerspan'); 
          //Globals: 
          var timeExpired = false;

          // Test time in seconds
          var totalTime = secs + (mins * 60);

        var countDown = function (callback) { 
            var interval;
            interval = setInterval(function () {
                if (secs === 0) {
                    if (mins === 0) {
                        timerDisplay.text('0:00');
                        clearInterval(interval);
                        callback();
                        return;
                    } else {
                        mins--;
                        secs = 60;
                    }
                }
                var minute_text;
                if (mins > 0) {
                    minute_text = mins;
                } else {
                    minute_text = '0';
                }
                var second_text = secs < 10 ? ('0' + secs) : secs;

                timerDisplay.text(minute_text + ':' + second_text);
                secs--;
            }, 1000, timeUp);
        };

            // When time elapses: submit form
            var timeUp = function () { 
                alert("Time's Up!");
                timeExpired = true;
                var completed=1;
                $.ajax({
                  type:"POST",
                   url:"success.php",
                   data:{'userID':<?php echo $_SESSION['userID'];?>},
                   success: function (hasil) {
                      $('.response_div').html(hasil);
                   }  
                });
            };

            // Start the clock
            countDown(timeUp);

0 个答案:

没有答案