Home  >  Article  >  Web Front-end  >  How to use timer to implement countdown function in js

How to use timer to implement countdown function in js

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 10:03:573191browse

This time I will show you how to use jstimerto realize thecountdown function, js uses timer to realize the countdown functionNotesThere are Which ones, the following are practical cases, let’s take a look.

Date function

Countdown = use future time - present time

Question: The future time is 1970 milliseconds away - the present time is 1970 years 1

Just use the number of milliseconds in the future - the number of milliseconds now and continue to convert.

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title></title>
 <style>
  body{
   font-size:30px;
   text-align: center;
   color:red;
  }
 </style>
 <script>
  window.onload = function(){
   var demo = document.getElementById("demo");
   var endTime = new Date("2017/11/12 17:30:00"); // 最终时间
   setInterval(clock,1000); // 开启定时器
   function clock(){
    var nowTime = new Date(); // 一定是要获取最新的时间
    // console.log(nowTime.getTime()); 获得自己的毫秒
    var second = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
    // 用将来的时间毫秒 - 现在的毫秒 / 1000 得到的 还剩下的秒 可能处不断 取整
    // console.log(second);
     // 一小时 3600 秒
    // second / 3600 一共的小时数 /24 天数
    var d = parseInt(second / 3600 / 24); //天数
    //console.log(d);
    var h = parseInt(second / 3600 % 24) // 小时
    // console.log(h);
    var m = parseInt(second / 60 );
    //console.log(m);
    var s = parseInt(second ); // 当前的秒
    console.log(s);
    /* if(d<10)
    {
     d = "0" + d;
    }*/
    d<10 ? d="0"+d : d;
    h<10 ? h="0"+h : h;
    m<10 ? m="0"+m : m;
    s<10 ? s="0"+s : s;
    demo.innerHTML = "距离抢购时间还剩: "+d+"天 "+h+"小时 "+m+"分钟 "+s+"秒";
   }
  }
 </script>
</head>
<body>
<p id="demo"></p>
</body>
</html>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:



The above is the detailed content of How to use timer to implement countdown function in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn