js固定时间倒计时

JavaScript08

js固定时间倒计时,第1张

function countdown(when, callback){

    // 判断当前时间

    var now = Date.now()

    if(when < now){

        throw '开始时间不能小于当前时间'

    }

    // 如果大于当前时间,则过了相差的时间后再执行此函数

       else if(when > now){

        setTimeout(function(){

            countdown(when, callback)

        }, when - now)

    } else{

        // 开始倒计时,这里的逻辑你没有描述

    } 

}

注意,js的定时并不是完全准确的。所有的setXXX之类的延时函数都是等计算机空闲下来才会执行

var the_s = 188888//定义剩余时间, 必须用时间戳.单位为秒

setInterval(promote,1000)//每秒执行一次下面的函数

function promote() {

var d = Math.floor((the_s / 3600) / 24)

var g = Math.floor((the_s - d * 24 * 3600) / 3600)

var e = Math.floor((the_s - d * 24 * 3600 - g * 3600) / 60)

var f = (the_s - g * 3600) % 60

var html = "还剩<b>" + d + "</b>天<b>" + g + "</b>时<b>" + e + "</b>分<b>" + f + "</b>秒"

document.getElementById("divdown1").innerHTML = html//这个id是你想要显示的div的id

the_s--

}

我这个定时器比你的好, 用我的.  你只要定义了the_s和要显示在哪的id. 就可以用了.

如你要显示剩余4小时, 那么将4小时转化为秒: 4*60*60=14400, 就这样调用:

var the_s = 14400

setInterval(promote,1000)

就ok了. 记得要引用我的函数哟~