【练习|用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)
}
推荐阅读
- 练习|vue+element实现手机号验证码注册
- Python|python:while打印正三角形
- 牛客练习赛25 因数个数和
- Python|Python练习实例——星号三角形
- python输出棱形及对称三角
- 2.任何一个自然数m的立方均可写成m个连续奇数之和
- 2017年09月23日普级组 看电影
- 练习|如何对解压缩版的Tomcat进行启动