简体   繁体   English

在Javascript和PHP中实现计时器的最佳方法

[英]Best way to implement a timer in Javascript and php

I am developing a quiz application in php and Javascript. 我正在用php和Javascript开发测验应用程序。 The quiz starts when the user hits a submit button(I don't control when the quiz should start). 当用户点击提交按钮时,测验即开始(我不控制测验何时开始)。 The quiz should stop after a specific time (I decide that). 测验应在特定时间后停止(我决定是这样)。 I don't want to rely completely on the client computer to stop the time since the client pc time can be altered. 我不想完全依赖客户端计算机来停止时间,因为可以更改客户端计算机的时间。 The quiz should not restart on page refresh. 测验不应在页面刷新时重新启动。

I know setInterval and basic javascript. 我知道setInterval和基本的javascript。 The function I have developed so far works perfectly, but the quiz restarts on page refresh. 到目前为止,我开发的功能可以正常运行,但是测验会在页面刷新时重新启动。

function formatSecondsAsTime(secs) {
    var hours = Math.floor(secs / 3600);
    var minutes = Math.floor(secs / 60) - (hours * 60);
    var seconds = secs - (hours * 3600) - (minutes * 60);
    return hours + ':' + minutes + ':' + seconds;
}

function startTimer(mytime) {
    mytime = mytime.split(":");
    hrs = mytime[0];
    parseInt(hrs, 10);
    mins = mytime[1];
    parseInt(mins, 10)
    secs = mytime[2];
    parseInt(secs, 10);
    if (hrs > 0 || mins > 0 || secs > 0) {
        timerVar = setInterval(function () {
            if (secs > 0) //time is less than a minute
            {
                displayTime(hrs, mins, secs--);
            }
            else if (secs == 0 && mins > 0) {

                displayTime(hrs, mins = mins - 1, secs = secs + 59);
            }
            else if (secs == 0 && mins == 0 && hrs > 0) {
                displayTime(hrs--, mins = mins + 59, secs = secs + 59);
            }
            else if (secs == 0 && mins == 0 && hrs == 0) {
                clearTimeout(timerVar);
                displayTime(0, 0, 0);
            }
        }, 1000);
    }
    else {
        displayTime(0, 0, 0);
    }
}


function displayTime(hrs, mins, secs) {
    if (secs > 0 || hrs > 0 || mins > 0) {
        if ((secs.toString()).length < 2) secs = "0" + secs;
        if ((mins.toString()).length < 2) mins = "0" + mins;
        if ((hrs.toString()).length < 2) hrs = "0" + hrs;

        document.getElementById("quiztime").innerHTML = "Time remaining: " + hrs + ":" + mins + ":" + secs;
    }
    else {
        document.getElementById("quiztime").innerHTML = "Quiz has ended!";
        alert("Quiz has ended. Click ok to continue.");
        document.forms["answerForm"].submit();
    }
}

Please suggest me the best way to do it. 请建议我最好的方法。

Thank you. 谢谢。

One of the best ways to achieve this is the following: on the begin of the quiz, send an AJAX request to the server telling your PHP script that it's started. 实现此目的的最佳方法之一如下:在测验开始时,向服务器发送AJAX请求,告知您的PHP脚本已启动。 Your PHP script should store a session variable for that user holding the start time. 您的PHP脚本应为持有开始时间的该用户存储一个会话变量。 On submit of the quiz, check to make sure that the difference between the current time and the session stored start time is no greater than your allowed amount of time. 提交测验时,请检查以确保当前时间与会话存储的开始时间之间的时差不大于您允许的时间。

Session variables can't be edited or viewed by the client. 会话变量不能由客户端编辑或查看。 If the client loads the page in the middle of the quiz, set the JS timer amount to whatever time is left based on the start time in the session. 如果客户端在测验的中间加载页面,则根据会话中的开始时间将JS计时器数量设置为剩余的时间。

I'll suggest you to use cookies to determine if the current user is in some started quiz. 我建议您使用cookie来确定当前用户是否正在参加一些测验。 Ie when the user clicks submit you are setting a cookie with PHP and record the started time in a database. 即,当用户单击“提交”时,您将使用PHP设置cookie并将开始时间记录在数据库中。 Every time when the user visits the page you will check for that cookie and will fetch the record from the database. 每次用户访问页面时,您都会检查该cookie,并从数据库中获取记录。 That's how you will find out how much time is left till the end of the quiz. 这样一来,您便可以知道到测验结束还剩下多少时间。

Cookies are the key to remembering the start time. Cookies是记住开始时间的关键。 Set the start time in a cookie, in php on submit. 在cookie中设置开始时间,在提交时使用php。 This same time should be written to the page in a script element (then both the server and client will know the start time). 应该在脚本元素中将同一时间写入页面(然后服务器和客户端都将知道开始时间)。 To protect the cookie you can encrypt it server-side. 为了保护cookie,您可以在服务器端对其进行加密。 You can verify that the start time has not been tampered with by comparing the value in the cookie with the one in js (when the test completes). 您可以通过将cookie中的值与js中的值(测试完成时)进行比较来验证开始时间是否未被篡改。

If the page reloads and the cookie exists, pull the time from the cookie rather than setting new time. 如果页面重新加载并且cookie存在,请从cookie中拉出时间而不是设置新时间。

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

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