JavaScript JS倒计时
2019-08-31 07:04:29
296
0
这里输入引用文本数据库记录一个日期字段,取日期和服务器当前时间;`用服务器当前时间和本地当前时间做差`,本地js每秒执行一次用本地的时间加上时间差和取出的服务器的日期做比较倒计时(会有最初几百毫秒或者几秒请求的误差,但是有效避免页面放置很久会有几分钟甚至几小时的误差) ```javascript var serverNowTime = 时间戳; var stopTime = 时间戳; var localDifferenceTime = parseInt(serverNowTime - (new Date()).getTime()); var runTime = setInterval(function () { var timeDownDifference = parseInt(stopTime - (new Date()).getTime()) - localDifferenceTime; if (timeDownDifference > 2000) { $("#timeDifference").html(getTimeDifference(timeDownDifference)); $('.timeDifferenceBox').show(); } else { $('.timeDifferenceBox').hide(); window.clearInterval(runTime); } }, 1000); function getTimeDifference(period) { var monthLevelValue = 30 * 24 * 60 * 60 * 1000; var dayLevelValue = 24 * 60 * 60 * 1000; var hourLevelValue = 60 * 60 * 1000; var minuteLevelValue = 60 * 1000; var secondLevelValue = 1000; function getDifference(period) { var month = parseInt(getMonth(period)); var day = parseInt(getDay(period - month * monthLevelValue)); var hour = parseInt(getHour(period - month * monthLevelValue - day * dayLevelValue)); var minute = parseInt(getMinute(period - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue)); var second = parseInt(getSecond(period - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue - minute * minuteLevelValue)); var result = ""; if (month > 0) result = result + month + "月"; if (day > 0) result = result + day + "天"; result = result + hour + "时" + minute + "分" + second + "秒"; function getMonth(period) { return parseInt(period) / monthLevelValue; } function getDay(period) { return parseInt(period) / dayLevelValue; } function getHour(period) { return parseInt(period) / hourLevelValue; } function getMinute(period) { return parseInt(period) / minuteLevelValue; } function getSecond(period) { return parseInt(period) / secondLevelValue; } return result; } return getDifference(period); } ```