效果展示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> window.onload = function() { var interVal = setInterval(function(){ var endTime = 1558598070; if(endTime <= Date.parse(new Date())/1000){ clearInterval(interVal); }else{ var timeStr = timeInterval(endTime); console.log(timeStr); } },1000); // timeInterval2(1558596900) } var timeInterval = function(endTime){ var nowTime = Date.parse(new Date()); // 获取现在的时间的时间戳 var time = endTime - nowTime/1000; //时间差: var day = 0, hour = 0, minute = 0, second = 0, result = ''; if (time >= 0) { day = Math.floor(time / (60 * 60 * 24)); //相差天數 hour = Math.floor(time / (60 * 60))-day * 24; //相差小时 minute = Math.floor(time % 3600 / 60); //相差分钟 second = Math.floor(time % 3600 % 60); if (day<=9) {day = "0" + day;} if (hour<=9) {hour = "0" + hour;} if (minute<=9) {minute = "0" + minute;} if (second<=9) {second = "0" + second;} result = day + "天" + hour + ":" + minute + ":" + second; return result; } } var timeInterval2 = function(endTime){ var intervalName = setInterval(function(){ var nowTime = Date.parse(new Date()); // 获取现在的时间的时间戳 var time = endTime - nowTime/1000; //时间差: var day = 0, hour = 0, minute = 0, second = 0, result = ''; if (time >= 0) { day = Math.floor(time / (60 * 60 * 24)); //相差天數 hour = Math.floor(time / (60 * 60))-day * 24; //相差小时 minute = Math.floor(time % 3600 / 60); //相差分钟 second = Math.floor(time % 3600 % 60); if (day<=9) {day = "0" + day;} if (hour<=9) {hour = "0" + hour;} if (minute<=9) {minute = "0" + minute;} if (second<=9) {second = "0" + second;} result = day + "天" + hour + ":" + minute + ":" + second; console.log(result); } if(day==0 && hour==0 && minute==0 && second==0){ clearInterval(intervalName); } },1000); } </script> </html>