Reputation: 21
I'm trying to implement a counter into a website. The purpose of this counter is to represent how much oil is delivered by said company, and to count up by the litre. Code-wise, the logic is to add two every second as a visual representation of the amount of litres, got this bit working.
What I'm trying to do now is save that value so that on refresh, or for when somebody else visits the site, it continues from the current value rather than the original "start" value. I think I may need to use cookies but I've got myself stuck on how to do this, any ideas?
I've included my code for reference, thanks all!
var gaugeStart = 320000000;
var gaugePerSecond = 2;
var gaugeInterval = 500;
var gaugeCurrent = 513637030;
$(document).ready(function() {
$('#gaugeValue').html(commafy(gaugeCurrent));
var tick = setInterval(function() {
gaugeCurrent += Math.ceil((gaugeInterval/1000) * gaugePerSecond);
$('#gaugeValue').html(commafy(gaugeCurrent));
}, gaugeInterval);
document.cookie = gaugeCurrent;
});
function commafy( num ) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
https://jsfiddle.net/93byc54f/
Upvotes: 0
Views: 130
Reputation: 1
Using cookies will result in every client displaying a different number of litres. The best way to approach this would be to record the value at a specific time and then provided that we know the increment interval - to calculate the difference since that date.
var gaugeStart = 320000000;
var gaugePerSecond = 2;
var gaugeInterval = 500;
var gaugeCurrent = 513637030;
var now = new Date();
var then = new Date("2016-01-01 00:00:00");
var secondsSince = Math.floor((now - then) / 1000);
var gaugeAmoountSince = secondsSince*4;
gaugeCurrent += gaugeAmoountSince;
$(document).ready(function() {
$('#gaugeValue').html(commafy(gaugeCurrent));
var tick = setInterval(function() {
gaugeCurrent += Math.ceil((gaugeInterval/1000) * gaugePerSecond);
$('#gaugeValue').html(commafy(gaugeCurrent));
}, gaugeInterval);
document.cookie = gaugeCurrent;
});
function commafy( num ) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
https://jsfiddle.net/mb0pv4ea/
Hope this helps.
Upvotes: 0
Reputation: 16031
If as you say
somebody else visits the site,
this is the exact place, where you need to realize, that you must store this information on the server side.
If you need to do this only for a single user, then localStorage
should be your obvious choice.
Upvotes: 1