Christopher Krohn Christopher Krohn - 28 days ago 5
Javascript Question

Run a counter that is displayed on website

I want to run a counter on the back end of a website, so that it is constantly counting. I made a javascript counter (http://directinvent.com/counter/) which displays the desired result, although this resets whenever the site is loaded for each individual user.

The idea is simple enough. Run the counter back end and display the result live on front end. Any ideas on how this can be done?

Answer

The same way you would do a Timer in Javascript. You store when you start your counter. Then you recalulate the result on every update (request). No need to do the math every 1/10s. If nobody ask, this is useless.

Basicly, this will look like this :

long startTime = storeTimeFor(User);
return (currentTimeInSec - startTimeInSec) * incrementationPerSec

With this, you only need to store the startTime for each user (in database, file, or in cache if you want). On reset, just store the currentTime again.

This is how you would do a timer in lots of langage because incrementing a value every seconds (using a sleep(1000)) would not be precise since your thread will not be running all the time, your are not alone on the machine ;)

EDIT :

On the client side, I would not call to much the server, just ask the value store and do the math from the client with the same logic. Using a timeout to do the math over and over every X ms. See how to create a timer in Javascript if need, only the value calculate would change here.

Comments