javascript reload only once

merxie

I don't know javascript and I have tried to find an answer on this before posting.

$(function(){
    $('body').fadeIn(1000);
    setTimeout(function(){
        $('body').fadeOut(2000, function(){
            location.reload(true);
        });
    }, 5000); // 5 seconds for demo
});

See the code in work here: http://jsfiddle.net/7duedzkb/5/

This code reloads a page every 5 seconds. I'd want to modify it to reload a page only once, basically it will reload the page after 5 secs and then stops the reload loop. I need this on a aggregator type of site where at first page opening the feeds are loaded from cache for speed issues.

Can you help? Much appreciated. Thank you

Marcos Pérez Gude

You must reload only if a certain condition is true. For example, you can save in sessionStorage a flag and read if exists don't reload.

var store = window.sessionStorage;
$(function(){
    $('body').fadeIn(1000);
    if(!store.getItem("reloaded")) {
       setTimeout(function(){
           $('body').fadeOut(2000, function(){
               store.setItem("reloaded", "true");
               location.reload(true);
           });
       }, 5000); // 5 seconds for demo
    }
});

It's better session storage instead of localstorage, because the next time user comes to the page the flag will be setted.

EDIT

Solution storing the URL of the page (assuming the URLs are unique):

var store = window.sessionStorage;
var page = window.location.href;
$(function(){
    $('body').fadeIn(1000);
    if(!store.getItem("reloaded-"+page)) {
       setTimeout(function(){
           $('body').fadeOut(2000, function(){
               store.setItem("reloaded-"+page, "true");
               location.reload(true);
           });
       }, 5000); // 5 seconds for demo
    }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related