Every  Thing
Every Thing

Reputation: 333

How to make timer in JavaScript?

I want reverse timer for session time out. I got one code on codepen. This code is clockwise timer , I tried to make it anti-clock wise , I am failed. Please suggest me. I want to make 1 hour or 59min 59sec time out. Please help me Here is the codepen demo.

if((intervalCounter%1000)==0){
                currentTime += 1000;
                var appendHour = currentTime / (1000 * 60 * 60) | 0; 
                var appendMinute = currentTime % (1000 * 60 * 60) / (1000 * 60) | 0;
                var appendSecond = currentTime  % (1000 * 60) / 1000 | 0;

                appendHour = appendHour < 10 ? "0" + appendHour : appendHour;
                appendMinute = appendMinute < 10 ? "0" + appendMinute : appendMinute;
                appendSecond = appendSecond < 10 ? "0" + appendSecond : appendSecond;
                hour.html(appendHour);
                min.html(appendMinute);
                sec.html(appendSecond);

                }

Upvotes: 3

Views: 375

Answers (1)

Shivani Sonagara
Shivani Sonagara

Reputation: 1307

This code is work for anti-clockwise direction.I hope you get some idea from below example.

// Set the date we're counting down to
var countDownDate = new Date("July 5, 2019 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
    
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>

Upvotes: 2

Related Questions