3

I am getting current time when page loads and I want to start timer from current time. How can I do this?

Here is my current script:

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("#timer").text(time);
Florian Lemaitre
  • 5,905
  • 2
  • 21
  • 44
Saad Ahmed
  • 43
  • 4

2 Answers2

1

Are you looking for this?

var dt = new Date();
setInterval(function() {
  dt.setSeconds(dt.getSeconds() + 1);
  var time = pad(dt.getHours(), 2) + ":" + pad(dt.getMinutes(), 2) + ":" + pad(dt.getSeconds(), 2);
  $("#timer").text(time);
}, 1000)

function pad(num, size) {
  var s = num + "";
  while (s.length < size) s = "0" + s;
  return s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
rrk
  • 15,677
  • 4
  • 29
  • 45
  • no this code is getting current machine time. i will be given with server sent time. i will loop on it and display time just like the clock – Saad Ahmed Feb 22 '16 at 10:44
  • I added this code but this only works when page is active i mean for the duration until page is focused but when i navigate to other tag time stops and when i navigate back to this tab instead of 1 minute it only passed 10 or 12 seconds. Kindly help me with this. I think browser lows it down in priority – Saad Ahmed Feb 22 '16 at 12:22
  • @SaadAhmed when you go to some page and come back, then you need to get the time from server again. – rrk Feb 22 '16 at 12:25
  • ok i got it but isn't there any other solution without taking input again from server? – Saad Ahmed Feb 22 '16 at 12:27
  • @SaadAhmed I don't believe so. I am not able to think of any fail safe techniques. – rrk Feb 22 '16 at 12:28
0

You can put these 3 lines in a fuction and use setInterval()

function showTime(){
    //var dt = new Date();
    //var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();

    //var time = [add a ajax call to your server and get the time in string format.]
    $("#timer").text(time);
}
setInterval(showTime,1000);

So the fuction is called each second and the div is updated with current time.

SamGhatak
  • 1,487
  • 1
  • 16
  • 27