javascript - 倒数计时器启动和停止

时间:2016-08-22 13:12:35

标签: javascript

我创建了在线考试系统。

我的问题:我点击应用按钮而不是倒数计时器启动,有时浏览器页面关闭,然后我点击相同的考试名称然后倒数计时器继续,而不是开始开始。屏幕截图

screenshot-1

screenshot -2

查看:

    <h2><p style="float: right" id="countdown"></p></h2>

<a href="<?php echo base_url(); ?>student/Examinations/apply_examinations/<?php echo $value['examination_test_id']; ?>" class="btn btn-primary" id="apply" onclick="resetCountdownInLocalStorage();">Apply</a>

    <script>
        $(document).ready(function () {
    $examination_test_id = $("#examination_test_id").val();
            $time_limit = $("#time_limit").val();
            var d = new Date($time_limit);
            var hours = d.getHours();
            var minute = d.getMinutes();
            var minutes = hours * 60 + minute;
            var seconds = 60 * minutes;

            if (typeof (Storage) !== "undefined") {
                if (sessionStorage.seconds) {
                    seconds = sessionStorage.seconds;
                }
            }
            function secondPassed() {
                var hours = Math.floor(seconds / 3600);
                var minutes = Math.floor((seconds - (hours * 3600)) / 60);
                //   var remainingSeconds = seconds - (hours * 3600) - (minutes * 60);
                var remainingSeconds = seconds % 60;

                if (remainingSeconds < 10) {
                    remainingSeconds = "0" + remainingSeconds;
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }

                if (typeof (Storage) !== "undefined") {
                    sessionStorage.setItem("seconds", seconds);
                }

                document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;

                if (seconds == 0) {
                    clearInterval(myVar);
                    document.getElementById('countdown').innerHTML = alert('Timeout');
                    window.location.href = base_url + "student/Examinations/check_answer/" + $examination_test_id;

                    if (typeof (Storage) !== "undefined") {
                        sessionStorage.removeItem("seconds");
                    }
                } else {
                    seconds--;
                }
            }
            var myVar = setInterval(secondPassed, 1000);
        });

function resetCountdownInLocalStorage() {
        sessionStorage.removeItem("seconds");
    }
    </script>

1 个答案:

答案 0 :(得分:0)

根据此link

,可能取决于浏览器
  

浏览上下文的生命周期可能与生命周期无关   用户代理可能支持的实际用户代理进程本身   重启后恢复会话。

我认为您可能必须在关闭选项卡上清理会话stroage。