<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js实现截取时间段进行倒计时和指定时间倒计时</title>
</head>
<body>
<div id="leftTime"></div>
<script>
let countDownBar = null; // 定时器句柄
const CURRENTTIME = new Date(); // 当前时间
const TIMEOUT_LIMIT = 7200000; // 2小时 ms
let orderCreatedTime = 0; // 计算时间差
function countDownServer(time) {
let leftTime = null;
if (time) {
let flag = CURRENTTIME - time >= TIMEOUT_LIMIT ? 0 : (TIMEOUT_LIMIT - (CURRENTTIME - time));
leftTime = new Date((CURRENTTIME.getTime() + flag)) - (new Date());
} else {
leftTime = new Date((CURRENTTIME.getTime() + TIMEOUT_LIMIT)) - (new Date());
}
let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10),
hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10),
minutes = parseInt(leftTime / 1000 / 60 % 60, 10),
seconds = parseInt(leftTime / 1000 % 60, 10);
if (seconds < 0) {
// 执行具体逻辑
clearTimeout(countDownBar);
return false;
}
days = fix(days, 2);
hours = fix(hours, 2);
minutes = fix(minutes, 2);
seconds = fix(seconds, 2);
countDownBar = setTimeout(function() {
countDownServer(orderCreatedTime);
}.bind(this), 1000);
let countDown = {
h: hours,
m: minutes,
s: seconds,
d: days
};
console.log(countDown);
//document.body.innerHTML='剩余时间:'+countDown.d+'天'+countDown.h+'小时'+countDown.m+'分钟'+countDown.s+'秒';
document.getElementById("leftTime").innerHTML='剩余时间:'+countDown.d+'天'+countDown.h+'小时'+countDown.m+'分钟'+countDown.s+'秒';
}
function fix(num, length) {
return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}
// countDownServer(); // 开启两小时倒计时
orderCreatedTime = new Date("2020/05/21 13:30:26"); // 创建时间
// 通过获取创建时间和现在的时间,得到两者的毫秒差值,使用差值进行倒计时(限制时间两小时内)
countDownServer(orderCreatedTime); // 使用指定时间
</script>
</body>
</html>
原文链接:
https://blog.csdn.net/qq_15253407/article/details/87350775
参考其他链接:
https://www.cnblogs.com/wanlibingfeng/p/5938619.html
https://blog.csdn.net/qq_44075557/article/details/103096899