JavaScript 中的倒数和倒数计时器

countup and countdown timer in javascript

本文关键字:倒数 计时器 JavaScript      更新时间:2023-09-26

我们在我们的网站上有一个在线测验部分,它有一个JavaScript代码,可以计算我们的测试人员参与特定测试的时间:

小提琴

此代码中的 526 表示从测验开始经过的秒

document.writeln("<span id='"time_online1'"></span>");
zi_inceput1 = new Date();
ceas_start1 = zi_inceput1.getTime();
function initStopwatch1() {
    var timp_pe_pag1 = new Date();
    return ((timp_pe_pag1.getTime() + (1000 * 526) - ceas_start1) / 1000);
}
var time = 5 * 60;
function getSecs1() {
    var tSecs1 = Math.round(initStopwatch1());
    var iSecs1 = time - tSecs1 % 60;
    var tMins1 = Math.round(iSecs1 / 60);
    var iMins1 = time - tMins1 % 60;
    var sSecs1 = iSecs1 % 60;
    var sMins1 = iMins1 % 60;

    if (sMins1 === '0' && sSecs1 === '0') {
        alert('time is up and you can not continue, the test is submited.');
        document.getElementById('time_online1').innerHTML = "times up";
        document.qs.submit();
    } else {
        document.getElementById('time_online1').innerHTML = sMins1 + ":" + sSecs1;
        window.setTimeout('getSecs1()', 1000);
    }
}
window.setTimeout('getSecs1()', 1000)

现在我想添加一个名为"测试时间限制"的新功能,例如用户只有 60 分钟的时间来进行测试:所以计数器应该开始倒计时。

嗨,

这是您修改的函数,可以倒计时功能
爪哇语

document.writeln("<span id='"time_online1'"></span>");
zi_inceput1 = new Date();
ceas_start1 = zi_inceput1.getTime();
function initStopwatch1() {
    var timp_pe_pag1 = new Date();
    return ((timp_pe_pag1.getTime() + (1000 * 0) - ceas_start1) / 1000);
}
var tim = 05;
function getSecs1() {
    var tSecs1 = Math.round(initStopwatch1());
    if((tim-tSecs1)>=0)
    {
    var iSecs1 = (tim-tSecs1) % 60;
    var iMins1 = Math.round((tSecs1 - 30) / 60);
    var iHour1 = Math.round((iMins1 - 30) / 60);
    var iMins1 = iMins1 % 60;
    var min = Math.floor((tim-tSecs1) / 60);
    var iHour1 = iHour1 % 24;
    var sSecs1 = "" + ((iSecs1 > 9) ? iSecs1 : "0" + iSecs1);
    var sMins1 = "" + ((iMins1 > 9) ? iMins1 : "0" + iMins1);
    var sHour1 = "" + ((iHour1 > 9) ? iHour1 : "0" + iHour1);
    document.getElementById('time_online1').innerHTML = min + ":" + sSecs1;
    window.setTimeout('getSecs1()', 1000);
}
else
    alert("time up");
}
window.setTimeout('getSecs1()', 1000)​

您可以在 JSFIDDLE 上测试解决方案.这是否完成了您的要求,伙计..

更新了西北。