CountDown计时器使用Javascript

时间:2014-08-14 05:52:58

标签: javascript asp.net-mvc-4 timer

我正在进行在线考试我只是想在考试开始时启动计时器,并希望在考试结束时结束我在我的cotroller上的终结时间和即时通讯终止时间我想在系统时间和结束时间之间启动计时器< / p>

控制器

public ActionResult TestStarted(int TestId,DateTime End_Time)
        {
            ViewBag.ct = 0;
            ViewBag.TestId = TestId;

            EAssessmentNew.BAL.StudentBal studBal = new EAssessmentNew.BAL.StudentBal();
            EAssessmentNew.Dal.Student_Answer_Master _studAnsdal = new       EAssessmentNew.Dal.Student_Answer_Master();


            ViewBag.EndTime = End_Time;
        }

查看

<script type="text/javascript">





    var days, hours, minutes, seconds;


    var countdown = document.getElementById("lblCtime");


setInterval(function () {


    var current_date = new Date().getTime();
    var seconds_left = ( @ViewBag.EndTime - current_date) / 1000;


    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);


    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  

}, 1000);
</script>

假设我有EndTime 1:00 PM和系统时间12:00 PM我怎么能在这两次启动计时器,因为我想将我的EndTime 1:00 PM转换为毫秒,因为我的脚本中的当前日期返回我的时间毫秒。

1 个答案:

答案 0 :(得分:2)

您需要做的是每当用户点击“给予考试”时,将时间添加到您要给他的考试持续时间(即考试开始时间下午1点,并且您要给予用户1小时的完成时间)考试然后你需要通过时间1PM + 1小时更多,所以它将从该日期时间开始计算完成考试)并将此作为结束日期传递给此功能

<script>
    var end = new Date('08/14/2014 12:00 PM');

        var _second = 1000;
        var _minute = _second * 60;
        var _hour = _minute * 60;
        var _day = _hour * 24;
        var timer;

        function showRemaining() {
            var now = new Date();
            var distance = end - now;
            if (distance < 0) {

                clearInterval(timer);
                document.getElementById('countdown').innerHTML = 'EXPIRED!';

                return;
            }
            var days = Math.floor(distance / _day);
            var hours = Math.floor((distance % _day) / _hour);
            var minutes = Math.floor((distance % _hour) / _minute);
            var seconds = Math.floor((distance % _minute) / _second);

            document.getElementById('countdown').innerHTML = days + 'days ';
            document.getElementById('countdown').innerHTML += hours + 'hrs ';
            document.getElementById('countdown').innerHTML += minutes + 'mins ';
            document.getElementById('countdown').innerHTML += seconds + 'secs';
        }

        timer = setInterval(showRemaining, 1000);
</script>

结束日期将根据服务器日期时间自动计算,您无需担心当地时间。

DEMO1

DEMO2