CountUp to a Specified number without reset - javascript

I am trying to create a Countup counter Starting from 1 to 10000 and i do not want it to reset when user refreshes the page or cancels the page. The Counter should start from 1 for every user that visits the page and keep running in background till it gets to 10000 even if the page is closed.
I have written the page below which;
Starts from the specified number for every new visitor
Saves the progress and does not reset when page is refreshed, however
It does not keep counting when page is closed and starts from the last progress when user closes the tab and comes back later. My code is
function countUp() {
var countEl = document.querySelector('.counter');
var countBar = document.querySelector('.progress-bar');
var x = parseInt(localStorage.getItem('lastCount')) - 1 || 1;
var y = countEl.dataset.to;
var z = countBar.dataset.to;
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
}
localStorage.setItem('lastCount', x);
}
var timer = window.setInterval(addNum, 1000);
localStorage.setItem("addNum", counter);
toggleBtn.addEventListener('click', function(){
countUp();
toggleBtn.classList.add('hidden');
});
}
countUp();</script>
<body onload=countUp();>
<div class="counter" data-from="0" data-to="10000000"></div>
<div class="progress-bar" data-from="0" data-to="10000000"></div>
</body>

It's difficult to show an example on StackOverflow because it doesn't let you fiddle with localStorage but, it sounds like you want something like:
When a user visits the page check localStorage for a timestamp.
If timestamp exists, go to step 4
Timestamp doesn't exist so get the current timestamp and stash it in localStorage.
Get the current timestamp. Subtract the timestamp from before. If over 10,000, stop, you're done.
Display difference calculated in step 4.
Start a 1 second timer, when time is up, go to step 4.
Something along those lines should work even if they refresh the page and since you are calculating from the original timestamp it will "count" in the background even if the page is closed.
window.addEventListener("DOMContentLoaded", () => {
const start = localStorage.getItem("timestamp") || Date.now();
localStorage.setItem("timestamp", start);
function tick() {
const now = Date.now();
const seconds = Math.floor((now - start) / 1000);
const display = document.getElementById("display");
if (seconds > 10000) return display.innerHTML = "We're done";
display.innerHTML = seconds;
setTimeout(tick, 1000);
}
tick();
});
<div id="display"></div>

So, client-side code can't normally execute when a client-side javascript page is closed.
What you could do, however, is calculate where the timer should be then next time it is loaded.
For example, in your addNum() function, you could in addition to the last count, also store the current date (and time).
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
}
localStorage.setItem('lastCount', x);
localStorage.setItem('lastDate', new Date());
}
Then, when your code starts, you can retrieve lastDate, and then subtract the current Date() from it.
Then use that to add the difference to your counter.
function countUp() {
let storedCount = parseInt(localStorage.getItem('lastCount'));
let storedDate = Date.parse(localStorage.getItem('lastDate'));
let now = new Date()
let diffSeconds = (now.getTime() - storedDate.getTime()) / 1000;
let storedCount += diffSeconds;
var countEl = document.querySelector('.counter');
var countBar = document.querySelector('.progress-bar');
var x = storedCount - 1 || 1;
var y = countEl.dataset.to;
var z = countBar.dataset.to;
}
I'm sure there are some more changes required to make it work with your code, but the idea is to store the current time so that when the page is closed and reopened, you can 'adjust' the count to catch up to what it should be.

What you want here is not possible just from the client-side code, there is no way for 2 different machines to share that information at all.
Here's the thing though, you can do this with a backend where the database gets updated every time a new IP hits the server. Note with this approach, a user here is one system and not different browsers or sessions.
To update this real-time for someone who is already on the website, run a timer and call an API that specifically gives you the count. Therefore the page gets updated frequently. You can also do this with react-query as it comes with inbuilt functions to do all this.

Related

How Can I make millisecond Unique?

I'm using NodeJs.
I received constantly request from server.
I'm added some variable like createdTime to it and saved to the database.
when I sorted data by createdTime in some case It is not reliable, It is Repeated
How can I make differentiate between them ?
I do not want to count request.
I do not like to change timestamp's format.
var createdTime = new Date().getTime();
Here's a method of combining a counter with the current time to allow you to have as many as 1000 separate transactions within the same ms that are all uniquely numbered, but still a time-based value.
And, here's a working snippet to illustrate:
// this guarantees a unique time-based id
// as long as you don't have more than 1000
// requests in the same ms
var getTransactionID = (function() {
var lastTime, counter = 0;
return function() {
var now = Date.now();
if (now !== lastTime) {
lastTime = now;
counter = 0;
} else {
++counter;
}
return (now * 1000) + counter;
}
})();
for (var i = 0; i < 100; i++) {
document.write(getTransactionID() + "<br>");
}
If you want something that is likely to work across clusters, you can use process.hrtime() to use the high resolution timer instead of the counter and then make the id be a string that could be parsed into a relative time if needed. Since this requires node.js, I can't make a working snippet here in the browser, but here's the idea:
// this makes a unique time-based id
function getTransactionID () {
var now = Date.now();
var hrtime = process.hrtime();
return now + "." + ((hrtime[0] * 1e9) + hrtime[1]);
}
Due to my low rep I can't add a comment but it looks like you are needing to go beyond milliseconds.Maybe this stackoverflow question can help you
How to get a microtime in Node.js?

Finishing multiple animations in the same time

I have four '.dist' elements. They have a different preloaded data (exactly: 57 , 27 , 17 , 244). I want to animate incrementing, and I wrote this code:
$('.dist').each(function() {
var count = parseInt($(this).text())
var incr = 0
var that = $(this)
var animation_time = 500
var interv = animation_time / count
$(this).text('0')
var fd = setInterval(function() {
if (incr < count){
incr++
that.text(parseInt(incr))
}
} , interv)
console.log(interv)
})
The problem: The biggest value finishes 100 light years after the rest.
Console.log (directly from this code) returns:
8.928571428571429
18.51851851851852
29.41176470588235
2.0491803278688523
Thats the values which I/We expected, but I think every interval has a specific delay, but I dont't know how to detect and correct that delay.
I want to finish all of incrementations from 0 to 'var count' in time ~= 500ms. I want to start all of incrementations in the same time, and finish every one in the same time.
Sorry for my primitive querstion but I started my adventure with js/jq only 6 months ago, and I can't find the answer by google. Maybe I'm retarted or something. Thanks for help.
edit: html
<div class="info back2 border corners1">
<span class="dist">56</span> seriali<br>
<span class="dist">27</span> obejrzanych<br>
<span class="dist">17</span> oczekuje<br>
<span class="dist">244</span> sezonów<br>
</div>
You have two problems: One is that you end up with a very small interval, and second that the calculated interval becomes a float. SetInterval can only handle whole milliseconds, not fractions, so your calculation will always be off. Better to set a start and end time and calculate the difference.
This is the most accurate way to do time calculations in Javascript anyways.
$('.dist').each(function() {
var count = parseInt($(this).text());
var incr = 0;
var that = $(this);
var animation_time = 500;
$(this).text('0');
var time_start = new Date();
var fd = setInterval(function() {
var time_passed = new Date() - time_start;
if (time_passed >= animation_time) {
clearInterval(fd);
time_passed = animation_time;
}
that.text(Math.round(count*time_passed/animation_time));
} , 10);
})
http://jsfiddle.net/xau91msr/
Or if you don't care about the actual time for the animation and want browser stutters etc to not count as passed time you can increment time_passed yourself:
http://jsfiddle.net/jevjyf3m/
If you have a fixed number of steps and increment proportionally, then your counts will reach their ends together, also don't forget to clear the interval once the animation is complete.
http://jsfiddle.net/rtvtdasz/10
clearInterval(fd);

JavaScript Timer countdown to logout

I'm trying to make a countdown timer in JS that will change the value of a field every one minute (in the begining there is 20, and then change it to 19,18,17 etc), but it's not working correctly. It's changing value not every 60sec but I have a feel that it works random (sometimes it change value first time after 15 sec, another time it's 53). Any idea what I'm doing wrong? Here is the code:
function getTimeNow(){
var Time = new Date;
return Time.getHours()*60*60+Time.getMinutes()*60 + Time.getSeconds();
}
var start = getTimeNow();
var start_point = start%60;
var target = start+60*20;
function TimeOut(){
if((getTimeNow()-start)%60 == start_point && target>getTimeNow()){
var temp = jQuery('.Timer').html();
temp-=1;
jQuery('.Timer').html(temp);
}
setTimeout(TimeOut,1000);
}
You cannot count on the exact moment a timer function will be called. You need to change your logic to something more resilient to time shifts...
setInterval(function(){count.innerText = count.innerText - 1;},
60*1000);
this is also a lot shorter...

how to remain the count down time not beginning at first each time?

$(function() {
var count = 20;
countdown = setInterval(function() {
$("p.countdown").html(count + "seconds remailing!");
if (count == 0) {
window.location = 'http://stackoverflow.com/';
}
count--;
}, 1000);
});​
<p class="countdown">
Each time when i refresh the browser, the count down is beginning at 20. i want to when i refresh the browser. the count number not beginning at 20 each time. it begins from the actually time it beginning, how to do some changes to the code?
Probably the best method would be to store the current time in a cookie (or some other local storage), and check for it on page load. If it's present, use it. If it's not, start from 20.
To avoid the complexities of managing cross-browser storage, you could use amplify.store. Simply update the value with each iteration of your interval.
Setting values is pretty trivial:
amplify.store( 'countdown', count );
As is getting them at a later time:
amplify.store( 'countdown' );
Your code would look something like this:
$(function() {
// Pick up where we left off, or start from 20
var count = amplify.store('count') || 20;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remailing!");
if (count <= 0) {
// Clear our stored value
amplify.store('count', null);
window.location = 'http://stackoverflow.com/';
}
// Update stored value
amplify.store('count', count--);
}, 1000);
});​
Demo: http://jsfiddle.net/yWTR7/ ( Hit 'Run' after a few seconds )
first save time (max time) in php session variable or in datbase, and fire ajax query each 1 second or any interval you like that will decrease the php variable's value. When new page is loaded, load the php variables value in javascript...
alternative
You can use cookies to store timer values.
Here's one with localstorage:
$(function() {
var count = localStorage.getItem('count') || 20,
countdown = setInterval(function() {
localStorage.setItem('count', count);
$("p.countdown").html(count + " seconds remaining!");
if (count === 0) {
clearInterval(countdown);
localStorage.removeItem('count');
window.location = 'http://stackoverflow.com/';
}
count--;
}, 1000);
});
​
​
FIDDLE

How to make a real Javascript timer

I'm looking for a way to manipulate animation without using libraries
and as usual I make a setTimeout in another setTimout in order to smooth the UI
but I want to make a more accurate function to do it, so if I want to make a 50ms-per-piece
animation, and I type:
............
sum=0,
copy=(new Date()).getMilliseconds()
function change(){
var curTime=(new Date()).getMilliseconds(),
diff=(1000+(curTime-copy))%1000 //caculate the time between each setTimeout
console.log("diff time spam: ",diff)
sum+=diff
copy=curTime
var cur=parseInt(p.style.width)
if (sum<47){//ignore small error
//if time sum is less than 47,since we want a 50ms-per animation
// we wait to count the sum to more than the number
console.log("still wating: ",sum)
}
else{
//here the sum is bigger what we want,so make the UI change
console.log("------------runing: ",sum)
sum=0 //reset the sum to caculate the next diff
if(cur < 100)
{
p.style.width=++cur+"px"
}
else{
clearInterval(temp)
}
}
}
var temp=setInterval(change,10)
I don't know the core thought of my code is right,anyone get some ideas about how to make a more accurate timer in most browser?
Set the JsFiddle url:
http://jsfiddle.net/lanston/Vzdau/1/
Looks too complicated to me, use setInterval and one start date, like:
var start = +new Date();
var frame = -1;
var timer = setInterval(checkIfNewFrame, 20);
function checkIfNewFrame () {
var diff = +new Date() - start;
var f = Math.floor(diff / 50);
if (f > frame) {
// use one of these, depending on whether skip or animate lost frames
++frame; // in case you do not skip
frame = f; // in case you do skip
moveAnimation();
}
}
function moveAnimation () {
... do whatever you want, there is new frame, clear timer past last one
}

Categories