javascript 使用 Java Script 的在线测验计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18427731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:53:29  来源:igfitidea点击:

online quiz timer using Java Script

javascripttimer

提问by user2644795

I am coding an online timed exam and for the timer to run I am using JS! The code for the timer to start and calculate the time and submit the exam when timer expires is as follows:

我正在编写一个在线定时考试,为了让计时器运行,我正在使用 JS!定时器超时后启动和计算时间并提交考试的代码如下:

<script>
 //Once the complete page is loaded the GIF image disappears and questions are displayed
function StartTimer() 
{
    document.getElementById('Loading').style.display = "none";
    document.getElementById('Loaded').style.display = "block";
    document.getElementById('1').style.display = "block";
    document.getElementById('qustn1').style.backgroundColor="#dd6e23";
}
    //Sets the Interval to the time 
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
function submitForm()
{
    document.getElementById("submit").submit();
}
function calculate_time()
{
    var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
    var dt = new Date(); // Create date object.
    var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
    var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
    var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
    var secs = total_time - (mins * 60); // Extract remainder seconds if any.
    if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
    document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
    // Check for end of time, stop clock and display message.
    if(mins <= 0)
    {
        if(secs <= 0 || mins < 0)
        {
            clearInterval(ct);
            document.getElementById("txt").value = "0:00";
            submitForm();
        }
    }
}

The above code runs well and even when the timer expires, the exam submits automatically. But, I am trying to call the setTimeOut() and setInterval() methods once the body is completely loaded i.e setInterval("calculate_time()",100); // Start clock. setTimeOut("submitForm()", <?php echo $time_limit; ?>);should be in the startTimer().

上面的代码运行良好,即使计时器到期,考试也会自动提交。但是,我试图在主体完全加载后调用 setTimeOut() 和 setInterval() 方法,即setInterval("calculate_time()",100); // Start clock. setTimeOut("submitForm()", <?php echo $time_limit; ?>);应该在 startTimer() 中。

    <body onload="StartTimer()">
    ......
    <script>
    .....
    function StartTimer() 
{
    document.getElementById('Loading').style.display = "none";
    document.getElementById('Loaded').style.display = "block";
    document.getElementById('1').style.display = "block";
    document.getElementById('qustn1').style.backgroundColor="#dd6e23";
    var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
.....
    </script>

But when I do this, I am unable to execute the code exactly. Even though timer reaches 0:00 the exam cannot be submitted, instead negative timer is running!! Please help me!!

但是当我这样做时,我无法准确地执行代码。即使计时器到达 0:00 也无法提交考试,而是负计时器正在运行!!请帮我!!

回答by Mohammad Dashti

The problem is incorrect scope for variable ctin the second code. Actually, you should put this variable in a context that is available for *calculate_time* function.

问题是第二个代码中变量ct 的范围不正确。实际上,您应该将此变量放在可用于 *calculate_time* 函数的上下文中。

For example, you can try out this code which moves variable ctto the out-most scope:

例如,您可以尝试将变量ct移动到最外作用域的代码:

<body onload="StartTimer()">
......
    <script>
    .....
    var ct = null;
    function StartTimer() {
        document.getElementById('Loading').style.display = "none";
        document.getElementById('Loaded').style.display = "block";
        document.getElementById('1').style.display = "block";
        document.getElementById('qustn1').style.backgroundColor="#dd6e23";
        ct = setInterval("calculate_time()",100); // Start clock.
        setTimeOut("submitForm()", <?php echo $time_limit; ?>);
    }

    function submitForm() {
        document.getElementById("submit").submit();
    }
    function calculate_time() {
        var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
        var dt = new Date(); // Create date object.
        var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
        var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
        var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
        var secs = total_time - (mins * 60); // Extract remainder seconds if any.
        if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
        document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
        // Check for end of time, stop clock and display message.
        if(mins <= 0) {
            if(secs <= 0 || mins < 0) {
                clearInterval(ct);
                document.getElementById("txt").value = "0:00";
                submitForm();
            }
        }
    }

    .....
    </script>
......
</body>

The best way to find the root of problems like this, is using a javascript debugger like FireBugthat will easily pinpoint the root of your problem.

找到此类问题根源的最佳方法是使用像FireBug这样的 javascript 调试器,它可以轻松查明问题的根源。

回答by Mahtab Alam

I worked on a Online Quiz app where I have to implement timer. I created one Javascript function that I call on body load

我开发了一个在线测验应用程序,我必须在其中实现计时器。我创建了一个 Javascript 函数,用于调用身体负荷

`< script language ="javascript" >
           var tim;       
           var min = '${sessionScope.min}';
           var sec = '${sessionScope.sec}';

        function customSubmit(someValue){  
         document.questionForm.minute.value = min;   
         document.questionForm.second.value = sec; 
         document.questionForm.submit();  
         }  

    function examTimer() {
        if (parseInt(sec) >0) {

            document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
            sec = parseInt(sec) - 1;                
            tim = setTimeout("examTimer()", 1000);
        }
        else {

            if (parseInt(min)==0 && parseInt(sec)==0){
                document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";
                 alert("Time Up");
                 document.questionForm.minute.value=0;
                 document.questionForm.second.value=0;
                 document.questionForm.submit();

             }

            if (parseInt(sec) == 0) {               
                document.getElementById("showtime").innerHTML = "Time Remaining :"+min+" Minutes ," + sec+" Seconds";                   
                min = parseInt(min) - 1;
                sec=59;
                tim = setTimeout("examTimer()", 1000);
            }

        }
    }
< /script>

` Value of variable min and sec are set by sessionVariable which hold the exam time in session.

` 变量 min 和 sec 的值由 sessionVariable 设置,它保存会话中的考试时间。

The complete application with Timer functionality is available here

具有定时器功能的完整应用程序可在此处获得

http://www.edureka.co/blog/creating-an-online-quiz-application-implementing-countdown-timer/

http://www.edureka.co/blog/creating-an-online-quiz-application-implementing-countdown-timer/