JavaScript 实现倒计时

代码如下

<script type="text/javascript">
        var millisecond;
        var sI;
        function initDate() {
            var endTime = new Date("2015/02/05 16:23:50");
            var startTime = new Date("2015/02/05 16:23:30");
            millisecond = endTime.getTime() - startTime.getTime();
            sI = setInterval("calculateTime()", 1000);
        }

        function calculateTime() {
            if (millisecond <= 0) {
                alert("结束了");
                clearInterval(sI);
            }
            else {
                show(millisecond);
                millisecond -= 1000;
            }
        }

        function show(millisecond) {
            var msecPerMinute = 1000 * 60;
            var msecPerHour = msecPerMinute * 60;
            var msecPerDay = msecPerHour * 24;

            var day = Math.floor(millisecond / msecPerDay);
            millisecond -= (day * msecPerDay);

            var hours = Math.floor(millisecond / msecPerHour);
            millisecond -= (hours * msecPerHour);

            var minutes = Math.floor(millisecond / msecPerMinute);
            millisecond -= (minutes * msecPerMinute);

            var seconds = 0;
            if (millisecond > 1000) {
                seconds = Math.floor(millisecond / 1000);
            }
            $("#show").text(day + "天" + hours + "时" + minutes + "分" + seconds + "秒");
        }

    </script>

调用部分:

    <a href="javascript:initDate();">显示</a>
    <div id="show"></div>
    </div>


你可能感兴趣的:(JavaScript)