3

i want to make a javascript clock which will start when ever a user login and will run until user logout

currentlty i am doing it with setInterval and calling it after every second and add 1 second into previous time . Is there any better solution ?

Note : Clock should also work even if user refresh browser

Ahsan Attari
  • 987
  • 3
  • 12
  • 26

1 Answers1

2

I would echo Rohit's Comment but for an alternative JS soloution I would use javascripts Date object. Something like the below:

var logInTime = new Date();

var logoutTime = new Date();

var loggedInLength = logoutTime.getTime() - logInTime.getTime();
var seconds = loggedInLength / 1000
var minutes = seconds / 60
var hours = minutes / 60

Just set the logInTime on login and the logoutTime on logout

jsFiddle

Edit: I missed your note about clock working through refresh, to implement this without using serverside code you could use either local storage as suggested or set a cookie.

document.cookie = 'logintime='+logInTime.getTime()

look at this SO answer on how to retrieve a cookie by name: Get Cookie By Name

Community
  • 1
  • 1
Joe1992
  • 458
  • 5
  • 20