How to save a static variable with Javascript even when refreshing page - javascript

In the following code, I would like to save chrono time even when i reload the page. The variable to save as static is "diff". Because i need my chrono to return me the las time saved when i redirect to the same page. this code is declared in the header section. This code is not doing so, how would I accomplish that?
`
<script language="JavaScript">enter code here
var startTime = 0
var start = 0
var end = 0
var diff = 0
var timerID = 0
function chrono(){
end = new Date()
diff = end - start
diff = new Date(diff)
var msec = diff.getMilliseconds()
var sec = diff.getSeconds()
var min = diff.getMinutes()
var hr = diff.getHours()-1
if (min < 10){
min = "0" + min
}
if (sec < 10){
sec = "0" + sec
}
if(msec < 10){
msec = "00" +msec
}
else if(msec < 100){
msec = "0" +msec
}
//alert(document.getElementById("chronotime").innerText);
/* document.getElementById("pps").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
document.getElementById("ppa").innerHTML = hr + ":" + min + ":" + sec + ":" + msec */
document.getElementById("chronotime").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
timerID = setTimeout("chrono()", 10)
}
function chronoStart(){
start = new Date()
chrono()
}
function chronoContinue(){
start = new Date()-diff
start = new Date(start)
chrono()
}
function chronoReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
start = new Date()
}
function chronoStopReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
document.chronoForm.startstop.onclick = chronoStart
}
function chronoStop(){
document.chronoForm.startstop.value = "start!"
document.chronoForm.startstop.onclick = chronoContinue
document.chronoForm.reset.onclick = chronoStopReset
clearTimeout(timerID)
}
</script>

You can not keep a variable alive after refresh as variables are created in window which will get reloaded after refresh.
var a = 10;
//You can access this variable as below
console.log(a);//1st way
console.log(window.a);//2nd Way
So when the page gets refreshed, window gets reloaded.
Try to save your variables in the form of cookie(Old Traditional way)
document.cookie="key=value; key=value....."
Other options exists are:(Comparatively new.)
in browser "HTML5 Web SQL Database"(Reference).
But some time ago, I tested and it was not working on ff.
Local Storage. Below is the syntax:
localStorage.setItem("start", "10");
The options discussed above are for client side. The value can also be saved at server side.

Within the scope of a page, there is no way to have variables that survive page reloads. You could attempt browser storage, but that's risky (user may have multiple windows/tabs open with the same page, resulting in confusion).
The top option is to keep date information on the server in the user's session context (store timer start date when first request is received).
Having that in the user's session, you will be able to detect that the user's timer had already started upon subsequent calls.
This option also shields you from potential problems linked to multiple tabs (though not multiple/different browsers)

you can use browser's localStorage to achieve this action. As javascript does not work cross domain, either you should use localstorage or some back-end to achieve this functionality.
However when you use localStorage, the user can open up it's console and can use the command, localStorage.clear() to clear all browser's storage, so latter option is more reliable.

// Set value
localStorage.setItem(saveDiff, diff);
window.onload = function() {
//retrieve value back after page load
var saveDiff = localStorage.getItem(differenceValue);
}

Related

CountUp to a Specified number without reset

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.

How keep or remember of set date even though page load

When we call 1st time we get the start date of today.Then we wants to set new date and we want to keep the new set date after we call 2nd times.I don't know how to keep history data of date that we set and want to use again.
setCalendar: function() {
var inqYYYY = todate.substring(0, 4);
var inqMM = todate.substring(4, 6);
var inqDD = todate.substring(6, 8);
var inqStrDt = formatter.date(webank.date_minus(todate, 6));
var inqEndDt = inqYYYY + "-" + inqMM + "-" + inqDD;
datePicker.setCalendar("#inq_str_dt");
$("#inq_str_dt").val(inqStrDt);
datePicker.setCalendar("#inq_end_dt");
$("#inq_end_dt").val(inqEndDt);
}
You can set the inqStrDt and inqEndDt into a localStorage ( A persistent storage having lifetime till reset browser storage and history).
You can set the value by
localStorage.setItem('inqStrDt ', inqStrDt);
You can read accoringly as well
let startDate = localStorage.getItem('inqStrDt ');
if(startDate ) {
\\do something
}

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?

How to write value in text file using Javascript

I'm working on a number of views per page using JavaScript.
<SCRIPT LANGUAGE="JavaScript">
<!--
var cookiec = document.cookie
if (cookiec != "") {
var eqchr = 0;
for (var cloop = 1; cloop <= cookiec.length; cloop++) {
if (cookiec.charAt(cloop) == "=") {
eqchr=(++cloop);
}
}
var cookiess = 0;
clength=cookiec.length;
cookies="";
for (cloop = eqchr; cloop < clength; cloop++) {
if (cookiec==";") {
cloop=clength;
}
else {
cookies = cookies + cookiec.charAt(cloop);
}
}
cookiess = parseInt(cookies);
document.write("[" + cookiess + "]");
cookiess++;
cookies = cookiess;
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=" + escape(cookies) + "; expires=" + expDate.toGMTString();
}
else {
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=2; expires=" + expDate.toGMTString();
document.write("[1]");
}
// -->
</SCRIPT>
I am using the above JavaScript to calculate the number of views per page and I want to write the data in a text file.
Do you have any suggestions?
If your JavaScript is running in a browser environment, I would highly recommend either using HTML5 localStorage for storing (key, value) pairs or using AJAX to communicate with a server instead of trying to access a file on the client machine which may potentially become a security/privacy issue. Below is a simple example of using localStorage to store a page view count:
if (localStorage.numberOfViews) {
localStorage.numberOfViews = Number(localStorage.numberOfViews) + 1;
} else {
localStorage.numberOfViews = 1;
}
Hope this helps!
Javascript, running in a normal web browser, has very very limited access to the local file system.
So modern web browsers will let you save data to a file in a specialized directory, isolated from everything else.
For the most part, using localStorage (as mentioned by the others), is your best bet.
If you are running under Windows you can create a specialized file called an '.HTA' which runs with the same kind of access and permissions that regular files use.
Attribute LANGUAGE="JavaScript" is deprecated. You can remove it.
Now, replying your question, you can do it with PHP. Send the data when the user enter the page, send it via AJAX to your server and proccess it with PHP.

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

Categories