Continual counter regardless of page refresh - javascript

I have this piece of jQuery that currently increments a number by one every 5 seconds. The problem I have is that its client side, therefore it resets every time you refresh the page.
Instead I'd like the counter to continue even if you are away from the site and regardless of how many times you refresh the page, which is why I thought a server side script such as PHP would be better suited to my use case. If not please suggest otherwise.
I've setup a working fiddle of what I currently have with jQuery: http://jsfiddle.net/f354bzy5/
What would be the PHP to recreate this affect that include my requirements above?
Here's the Jquery I'm using:
//Counter
var counter = 22000000000;
$(".count").html(counter);
setInterval(function () {
$(".count").html(counter);
++counter;
}, 5000);

Check this DEMO
//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
$(".count").html(counter);
++counter;
localStorage.setItem('counts',counter);
}, 1000);
Highlight on localStorage
localStorage is an implementation of the Storage Interface. It stores
data with no expiration date, and gets cleared only through
JavaScript, or clearing the Browser Cache / Locally Stored Data -
unlike cookie expiry.

Can you store counter in cookie.
document.cookie = counter.
so you can get last value from cookie, if user refresh the page.

It comes down to two simple choices for you. Just choose the right one which better fits your requirement:
Choose Cookie : If you want the server side to access the counter. Remember cookies are sent along with the requests by default.
Choose Local Storage : If you don't want to send the counter along with requests every time, you are supposed to go for local storage.

You could do it with localStorage. Here's how I am doing it. You can tweak it as you need.
//detecting support for localStorage.
if (window.localStorage) {
//counterValue already exists in localStorage? Let's use that or set to zero.
var counterValue = localStorage.counterValue || 0;
setInterval(function() {
//increment the counter and store updated vale in localStorage as well.
localStorage.counterValue = ++counterValue;
//put it in your HTML if you might
$(".count").html(counterValue);
}, 5000);
}

How about using localStorage with some utility functions? Bear in mind that this is a client side solution and the item would be wiped off when the user deletes the browser cache/local data etc.
function isLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
function setCounter(key, val) {
localStorage.setItem(key, val);
}
function getCounter(key) {
return parseInt(localStorage.getItem(key), 10);
}
(function() {
var key = "myCounter";
var counter = isLocalStorage() && getCounter(key) || 1;
var $placeholder = $(".count");
$placeholder.html(counter);
setInterval(function () {
counter++;
$placeholder.html(counter);
isLocalStorage() && setCounter(key, counter);
}, 2000);
}());
-- Demo --

Related

setInterval change Interval

Hello I am new in javascript, I am making chrome extension, this extension contains the setInterval command, I want to change the time with javascript to the textbox I have added to a website. This change should remain when I refresh the page, how can I do this.
My content script start document_end
var Refresh = setInterval(clickerStart,4000)
function clickerStart(){
var selection1 = document.querySelector("#\\30 ") !== null;
if (selection1) {
location.reload();
} else {
console.log("Islem Bulundu.");
};
}
//textbox
var Interval = document.createElement("INPUT");
Interval.setAttribute("type", "text");
Interval.setAttribute("value", " ");
document.body.appendChild(Interval);
If you are not handling with sensitive data, which I think it is the case, you can use localStorage or cookies to store and reuse data (the interval time) until the user returns to the page (after refreshing it or reopening it).
Here's an explanation on how to set cookies:
https://www.w3schools.com/js/js_cookies.asp

Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)

I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id.
This code only works in 1.html page, where the text I want to copy from is but not in 2.html file.
Here is my code. Note that it works if I store text inside localstorage setter second parameter.
$( document ).ready(function() {
var c1Title= $('#r1c1Title').text();
//changing c1Title to any String content like "test" will work
localStorage.setItem("t1",c1Title);
var result = localStorage.getItem("t1");
$("#title1").html(result);
alert(result);
});
Here is the complete demo I am working on Github:
You need to use either localStorage or cookies.
With localStorage
On the first page, use the following code:
localStorage.setItem("variableName", "variableContent")
That sets a localStorage variable of variableName for the domain, with the content variableContent. You can change these names and values to whatever you want, they are just used as an example
On the second page, get the value using the following code:
localStorage.getItem("variableName")
That will return the value stored in variableName, which is variableContent.
Notes
There is a 5MB limit on the amount of data you can store in localStorage.
You can remove items using localStorage.removeItem("variableName").
Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). This is important, as otherwise using any of these solutions may be illegal.
If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code)
If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN
For more information on localStorage, check out this article on MDN, or this one on W3Schools
Please try to use this code. It's better to use local storage.
Here you need to make sure that you are setting this local storage
value in parent html page or parent js file.
create local storage
localStorage.setItem("{itemlable}", {itemvalue});
localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());
Get local storage value
localStorage.getItem("{itemlable}")
alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp
If you wanted to store in div then follow this code.
Html Code
<div class="div_data"></div>
Js code:
$(document).ready(function () {
localStorage.setItem("variable1", "Value 1");
localStorage.setItem("variable2", "Value 2");
$(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
});
Hope this helps.
You can use local storage as mentioned in above comments. Please find below how to write in javascript.
Local Storage Pros and Cons
Pros:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity.
5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain.
This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
// Store value in local storage
localStorage.setItem("c1Title", $('#r1c1Title').text());
// Retrieve value in local storage
localStorage.getItem("c1Title");
Your html div
<div id="output"></div>
Add Javascript Code
$('#output').html(localStorage.getItem("c1Title"));
Let me know if it not works
Create a common.js file and modified this and save.
Session = (function () {
var instance;
function init() {
var sessionIdKey = "UserLoggedIn";
return {
// Public methods and variables.
set: function (sessionData) {
window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
return true;
},
get: function () {
var result = null;
try {
result = JSON.parse(window.localStorage.getItem(sessionIdKey));
} catch (e) { }
return result;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
function isSessionActive() {
var session = Session.getInstance().get();
if (session != null) {
return true;
}
else {
return false;
}
}
function clearSession() {
window.localStorage.clear();
window.localStorage.removeItem("CampolUserLoggedIn");
window.location.assign("/Account/Login.aspx");
}
Insert like this.
$(function () {
if (!isSessionActive()) {
var obj = {};
obj.ID = 1;
obj.Name = "Neeraj Pathak";
obj.OrganizationID = 1;
obj.Email = "npathak56#gmail.com";
Session.getInstance().set(obj);
}
///clearSession();
});
get like this way
LoggedinUserDetails = Session.getInstance().get();

How to make a jquery count-down timer that doesn't restart on refresh

I am creating a web template for sale, but I can't make timer count down, I don't how to make it. I need timer count down (when a date is added, it should be decreased), also it should not restart on refresh time or shut down time. Please help me to do this code... I will use it in my template.
If you are not working with a database, then you can use HTML5 localstorage. Store a variable on the users local machine if they have already visited. When the page loads, do a check of local storage for that variable. If it is not null, then don't init the timer as they have already been on the site.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Create localstoreage var:
var myStorage = localStorage;
If user loads page - store true in "visited"
localStorage.setItem('visited', 'true');
If visitor reloads page, check for visited == true, and if true, dont trigger timer.
var hasVisited = function() {
var didVisit = myStorage.getItem('visited');
if(didVisit == "true"){
//do nothing}
}else{
//start your timer
};

Counter variable does not persist when loading a new page

I want to use counter variable in javascript like static variable with timer. counter must decrease by 1 on every second. I m working on online exam. on answering a question new question comes on the same page. my problem starts when counter variable is initialized with new question(means new page). counter variable does not persists on new page...suggest any solution
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = 30000; // 30 min
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>
Javascript variables are not meant to outlive the current page load. The browser's Javascript engine executes the code on every page load (though most browsers cache the complied code), so client-side variables are lost whenever the page reloads.
There are several common methods to pass values from one page to another:
DOM storage
Cookies
Server-side variables via a GET or POST request
Whatever method you select, remember it needs to be adequately resilient to unwanted manipulation by the user.
Using ajax pass value from one to another page. use session to hold last remainTime thai is passed to next page
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = <cfoutput>#session.RemainTime#</cfoutput>;
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
$.get('linktosend.cfm',{counter:ExamTimer.counter},function(responseText)
{
// value of ExamTimer.counter send to linktosend.cfm and store in session.RemainTime
});
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>

jQuery event only every time interval

$(document).ready(function() {
$('#domain').change(function() {
//
});
});
The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).
However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.
So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.
How can I do that?
$(function() {
var timer = 0;
$("#domain").change(function() {
clearTimeout(timer);
timer = setTimeout(function(){
// Do stuff here
}, 2000);
});
});
$(document).ready(function() {
var ajaxQueue;
$('#domain').change(function() {
if(!ajaxQueue) {
ajaxQueue = setTimeout(function() {
/* your stuff */
ajaxQueue = null;
}, 2000);
}
});
});
What you really want to do is check how long since the last change event so you keep track of the number of milliseconds between events rather than make a call every 2 seconds.
$(document).ready(function() {
var lastreq = 0; //0 means there were never any requests sent
$('#domain').change(function() {
var d = new Date();
var currenttime = d.getTime(); //get the time of this change event
var interval = currenttime - lastreq; //how many milliseconds since the last request
if(interval >= 2000){ //more than 2 seconds
lastreq = currenttime; //set lastreq for next change event
//perform AJAX call
}
});
});
Off the top of my head without trying this in a browser. Something like this:
$('#domain').change(function() {
if (!this.sendToServer) { // some expando property I made up
var that = this;
this.sendToServer = setTimeout(function(that) {
// use "that" as a reference to your element that fired the onchange.
// Do your AJAX call here
that.sendToServer = undefined;
}, yourTimeoutTimeInMillis)
}
else {
clearTimeout(this.sendToServer);
}
});
two variables, charBuffer, sendFlag
Use a setTimeout to have a function be called every two seconds.
This function checks if the buffer has stuff in it.
If it does, it sends/empties the stuff and clears the sent flag (to false).
and It should also clear the timeout, and set it again
else it sets the flag (to true).
Everytime the user hits a key, store it in the buffer.
if the sent flag is clear (it's false), do nothing.
else (it's true) send/empty the stuff currently in the buffer and clear the flag (to false),
and It should also clear the timeout, and set it again
This will make it so that the first time you press a key, it is sent, and a minimum of 2 seconds must pass before it can send again.
Could use some tweaking, but i use this setup to do something similar.
I am coming across this problem more and more (the more i do UI ajax stuff) so i packaged this up into a plugin available here

Categories

Resources