用js计时器写倒计时

用js计时器写倒计时


写倒计时的思路:1,设置要到的时间。2,获取当前时间。3,计算时,分,秒,毫秒的时间差,4,用计时器把整个倒计时函数包装起来
1,倒计时内容部分

var timego=new Date("2019-6-30 12:00:00");//倒计时要到的时间
var timenow=new Date();//获取当前时间
var time=timego.getTime()-timenow.getTime();//时间差的所有毫秒数
var day=parseInt((time/1000/60/60/24)%30)
var hou=parseInt((time/1000/60/60)%24);
var min=parseInt((time/1000/60)%60);
var sec=parseInt((time/1000)%60);
var minsec=time%1000;
document.body.innerHTML=day+"天"+hou+"时"+(min<10?"0"+min:min)+"分"+(sec<10?"0"+ssec:sec)+"秒"+(minsec<10?"00"+minsec:minsec<100?"0"+minsec:minsec)+"毫秒";

2.用setTimeout()计时器包装的倒计时

 showtime();
    function showtime(){
        var timego=new Date("2019-06-30 12:00:00");
        var timenow=new Date();
        var time=timego.getTime()-timenow.getTime();
        var day=parseInt((time/1000/60/60/24)%30);
        var hou=parseInt((time/1000/60/60)%24);
        var min=parseInt((time/1000/60)%60);
        var sec=parseInt((time/1000)%60);
        var minsec=time%1000;
        document.body.innerHTML= day+"天"+hou+"时"+(min<10?"0"+min:min)+"分"+(sec<10?"0"+sec:sec)+"秒"
                +(minsec<10?"00"+minsec:minsec<100?"0"+minsec:minsec)+"毫秒";
    setTimeout(showtime,1);

用setInterval()计时器包装的倒计时

var timego=new Date("2019-6-30 12:00:00");
setInterval(function(){
  var timenow=new Date();//获取当前时间
  var time=timego.getTime()-timenow.getTime();//时间差的所有毫秒数
  var day=parseInt((time/1000/60/60/24)%30)
  var hou=parseInt((time/1000/60/60)%24);
  var min=parseInt((time/1000/60)%60);
  var sec=parseInt((time/1000)%60);
  var minsec=time%1000;
  document.body.innerHTML=day+"天"+hou+"时"+(min<10?"0"+min:min)+"分"+(sec<10?"0"+ssec:sec)+"秒"+(minsec<10?"00"+minsec:minsec<100?"0"+minsec:minsec)+"毫秒";
     },1)

用window.requestAnimationFrame()包装的计时器

    showtime();
    function showtime() {
        var timego = new Date("2019-06-30 12:00:00");
        var timenow = new Date();
        var time = timego.getTime() - timenow.getTime();
        var day = parseInt((time / 1000 / 60 / 60 / 24) % 30);
        var hou = parseInt((time / 1000 / 60 / 60) % 24);
        var min = parseInt((time / 1000 / 60) % 60);
        var sec = parseInt((time / 1000) % 60);
        var minsec = time % 1000;
        document.body.innerHTML = day + "天" + hou + "时" + (min < 10 ? "0" + min : min) + "分" + (sec < 10 ? "0" + sec : sec) + "秒"
                + (minsec < 10 ? "00" + minsec : minsec < 100 ? "0" + minsec : minsec) + "毫秒";
        setTimeout(function () {
            window.requestAnimationFrame(showtime)
        }, 1)
    }

你可能感兴趣的:(练习,倒计时)