0

I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?

Gibson
  • 780
  • 3
  • 14
  • 33

5 Answers5

3

try this:

setTimeout(function ()
    {
        if (self.name != '_refreshed_'){
        self.name = '_refreshed_';
        self.location.reload(true);
    } else {
        self.name = ''; 
    }
    }, 5000);
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
Homa
  • 3,417
  • 2
  • 19
  • 24
2

You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:

//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

//check if our query string is already set:
if(getQuerystring(r) !== 1){
  setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}

If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.

HellaMad
  • 5,294
  • 6
  • 31
  • 53
0

You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:

if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
    setTimeout(function ()
    {
        var search = location.search;
        location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
    }, 5000);
}

Demo: http://jsbin.com/ofawuz/edit

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:

How to wait 5 seconds with jQuery?

$(document).ready(function() {

        // Get data
        $.ajax({
            url : '/tommyStockExchange/Data',
            dataType : 'html',
            data : {
                'format' : 'H',
                'type' : 'E'
            },
            success : function(data) {
                $("#executions").html(data);
            },
            statusCode : {
                404 : function() {
                    alert('executions url 404 :(');
                }
            }

        });

    });
Community
  • 1
  • 1
Victor Parmar
  • 5,719
  • 6
  • 33
  • 36
0

Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.

Ming
  • 1,613
  • 12
  • 27