您的位置:首页 > Web前端 > JavaScript

js倒计时代码实现

2017-10-16 13:58 148 查看
/**
*
*返回剩余时间 {}
*/
function getTimeInfo(startTime, currentTime) {
var total = startTime.getTime() - currentTime.getTime();

return {
day: Math.floor(total/1000/60/60/24),  //天
hour: Math.floor(total/1000/60/60%24), //时
minute:  Math.floor(total/1000/60%60),  //分
second:  Math.floor(total/1000%60)  //秒
}
}

var firstLoadTime = true;

//动态倒计时处理
// startTime  开始时间 *
// ajaxUrl  $ ajaxUrl 存在时执行  不存在时或ajax出错时默认以本地时间为准
// attr  key
function executeShow(startTime, ajaxUrl, attr, log) {
var currentTime = new Date();

if (!firstLoadTime) {   //非首次获取时间
if(window.currentTime != null) {
currentTime = new Date(window.currentTime.getTime() + 1000);
}
} else {
try {
if (ajaxUrl != null && ajaxUrl.trim() != "") {  //通过ajax获取
var ajaxtime = $.ajax({
url: ajaxUrl,
async: false,
dataType: "json",
timeout: 1500,
success: function(data) {
try {
if (!attr) {
attr = "date";
}
var date = data[attr];  //获取输出的服务器时间
date = date.replace(/-/g, "/");
currentTime = new Date(date);
if (log && console) {
console.log("通过jquery初始化服务端时间成功");
}
} catch (e) {
currentTime = new Date();
}
},
complete: function(XMLHttpRequest, status) { //请求完成后最终执行参数
if (status == 'timeout') {  //超时
ajaxtime.abort(); //取消请求
currentTime = new Date();
} else if (status == 'error') {
currentTime = new Date();
}
}
});
}
} catch(e) {
currentTime = new Date();
}
firstLoadTime = false;
}
window.currentTime = currentTime;

setShowView(getTimeInfo(startTime, currentTime));   //设置页面显示的内容

setTimeout(function() {
executeShow(startTime, ajaxUrl, attr, log);
}, 1000);
}

//设置网页显示内容的函数,timeInfo为剩余时间json
function setShowView(timeInfo) {
console.log(timeInfo);
}

window.onload = function() {
var startTime = new Date("2017/11/11 00:00:00");  //设置活动开始的时间
executeShow(startTime);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript