Removing the setTimeout interval - javascript

After loading the document, I want to refresh the page once. So I wrote this code. It is working fine, but it is calling again and again. because I am refreshing same page. but I want to clear the interval after one time execution.
function refreshPage(){
document.location.reload(true);
alert('page is refresh.');
}
var interval = setTimeout('refreshPage()', 3000);

If you want it to work only once, whatever the delay, you could store in localStorage the fact you did it :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refreshDone'] = 'yes';
}
if (!localStorage['refreshDone']) {
setTimeout('refreshPage()', 3000);
}
But you can't simply clear the timeout or interval as the window variables are lost each time you reload the page.
As I'm not sure of your exact goal, in case you'd want to refresh if it hasn't been done recently, you could store a timestamp in localStorage :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refresh'] = new Date().getTime();
}
var lastTimeRefresh = parseInt(localStorage['refresh']||'0', 10);
if (new Date().getTime() - lastTimeRefresh > 30*60*1000) { // 30 minutes
setTimeout('refreshPage()', 3000);
}

You could set javascript cookies at the first refresh and then check if cookies are set or not, If it is not set please set the cookies and refresh the page, If not do nothing

Related

How do I set a maximum loading time for a page in JS?

I have a website which has multiple images which can take some time to load. To spare the users waiting, I have an option in the preferences that determines the maximum loading time of a page. If it exceeds the time limit, the user will be redirected to a fallback website.
For example, let's say the user set the loading time limit to 5 seconds. After 5 seconds (since page onload), if the document.readyState is not "complete," we redirect to the fallback site.
Here's what I've tried (didn't work):
setTimeout(check, 1);
function check(){
console.log("check");
if(document.readyState!="complete"){
stop();//Placeholder for redirect
console.log("stopped");
}else{
console.log("Loaded");
}
}
How can this be implemented using JavaScript?
Maybe this will help you:
let timeout = setTimeout(redirect, 5000);
const redirect = () => {
// redirect to the fallback
}
// jQuery approach
$(document).ready(() => {
clearTimeout(timeout);
});
// pure JS approach
window.onload = () => {
clearTimeout(timeout);
};

How can I create a session storage for my countdown timer so it's not reset after reloading the page?

This is my JavaScript file. I use the Countdown.js API , timer is a variable I receieve as a parameter.
var countDownCompleted = false;
var myCountdownTest = new Countdown({
time: timer,
width: 200,
height: 80,
onComplete: countdownComplete,
rangeHi: "minute"
});
function countdownComplete() {
countDownCompleted = true;
window.location.href = 'index.php';
}
What modification can I do so the countdown does not reset after reloading the page? I don't really understand how to create session storage.
localStorage and sessionStorage work just like normal variables. If you want your timer to pick up where it left off when the page is reloaded, you should store the current value every time the timer goes down.
Then, on every page load, you can check whether there's anything set inside localStorage and, if it is, start back from that value.

Execute a javascript code only on refreshing a page after 10 seconds?

I have a requirement where a java script code is there which makes a ajax call and save the user log in database on page load. But the problem is that every time when the user refresh the page the code is getting executed. I want to execute the statement only if the page is refreshed after 10 seconds not on every page refresh. I have to stop executing the code flow if the page is refreshed before 10 seconds.
This code executes all 10 seconds (or longer), triggered by a page reload:
You need to store the time (in localStorage), on reload check if now is later than stored time+ 10 seconds:
function store(){
//store time:
now=new Date().getTime();
localStorage.setItem("stored",now);
//your password storing
}
window.onload=function(){
now=new Date.getTime();
if(!localStorage.getItem("stored")){
//no time stored, so lets store
store();
return;
}
last=localStorage.getItem("stored");
//if now is later than last+10seconds
if(now>last+1000*60*10){
store();
}
}
Can you set cookies? Set the cookie value to current path, on redirect check the cookie value against the current URL. When it matches (so it is a refresh) you can trigger your 10 sec delay by
Logging = setTimout(function() {
Alert("10 seconds passed");
}, 10 * 1000);
To clear the timeout, use
clearTimeout(Logging)

Javascript time track

my requirement is 15 minutes after visiting the site, user will navigate to registration page. And I need to track the page even after open that page again, user will navigate to registration page.
As the requirement I think it will be possible with cookie, but I need to count the time of visiting the site. When site visiting minutes reach to 15 js will fire a function and there I can set the cookie and redirect.
Can any one please help me to track the site visiting minutes by js?
Although I agree with epoch, it can be done using localStorage:
(function (timer)
{
var now = new Date();
var redirect = function()
{
location.href = 'register url';
}
if (!localStorage.getItem('registrationMinutes'))
{
localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
}
if (localStorage.registrationMinutes <= +now)
{//on page load, check if 15 mins are up
return redirect();
}
timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})();
Just include this little function on all pages. You might want to set a cookie like userIsRegistered, and not set the timeout when the client has already been registered.Just know that this code will be sent to the client, and he or she is still free to disable cookies, JS,... and, I think, localStorage isn't supported by older IE browsers (there's a surprise!)If all this is a bit much, here's a simple copy-paste snippet:
(function (url,now,timer)
{
var redirect = function()
{
location.href = url;
}
if (!localStorage.getItem('registrationMinutes'))
{
localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
}
if (localStorage.registrationMinutes <= +now)
{//on page load, check if 15 mins are up
return redirect();
}
timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})('redirectUrl',new Date());
just replace the 'redirectUrl' string with your url, and it should work just fine. There is also no need to change variable names: it's all contained in this anonymous function's scope, so there is no conflict with variables declared in the parent scope.

Repeating/looping javascript function to check if a cookie has changed

I am trying to make a script that will repeat every 5 seconds.
The script that will be repeated will check to see if a cookie exists.
If the cookie does not exist, the page is redirected.
If the cookie does exist, nothing happens.
The cookies are working fine, my only problem is that it doesn't repeat!
I am using jQuery to identify/check the cookie and that is working fine.
I would like to know what is wrong with the code please.
I have looked online many times, but have had no luck in finding what I need.
This is the cookie plugin I use: https://github.com/carhartl/jquery-cookie
var checkcookie = $.cookie('myCookie');
checklogin();
function checklogin(){
setTimeout(function(){
if(checkcookie == null){
//if cookie not set
window.location.href='/';
}
else{
//if cookie set
}
}, 5000);
checklogin();//to recall the script after it is done
}
Or if any one has an alternative method of checking whether a cookie has changed, I would love to know!
It's working fine, but your cookie value not changing - it set once and forever. Try to include it in your setTimeout():
checklogin();
function checklogin(){
setTimeout(function(){
var checkcookie = $.cookie('myCookie');
if(checkcookie == null){
window.location.href='/';
}
else{
//if cookie set
}
}, 5000);
checklogin(); //to recall the script after it is done
}
If you're doing it that way the checklogin call has to be inside the setTimeout function otherwise it's called immediately everytime.
Also i'd use a setInterval instead, so you don't need you recursive function:
setInterval(function(){
if(checkcookie == null){
window.location.href='/';
}else{
//if cookie set
}
},5000);

Categories

Resources