Christopher Krohn Christopher Krohn - 1 year ago 54
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 ( 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 Source

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 ;)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download