Skip to content Skip to sidebar Skip to footer

Stop Javascript Auto Refresh After Fix Time For Example 1 Min

I am using setTimeout(javascript function) to auto refresh page for each 10 sec, and after one(1) min i want to stop auto refresh.For this i am using clearTimeout() javascript func

Solution 1:

Your variables t and j don't survive the page reload (they get whole new values when the page is reloaded, thus your stop() function and other logic can't work). If you want the "next" page reload to not auto-refresh any more, then you will have to use some state to communicate that that does survive the page reload. Your simple options are to set a cookie or use a URL parameter when you load the page again.

One method would be to set a cookie to keep track of reloads:

functionload()
{
    reloadCnt = getCookie("cnt") || 0;
    if (reloadCnt < 10) {
        setTimeout(function() {
            setCookie("cnt", reloadCnt + 1, 1);    // cookie that expires in one daywindow.location.reload();
        }, 10000);
    }
}

getCookie and setCookie are functions from this library though any cookie access library can be used.

Another option would be using a query parameter that you increase each time:

functionload()
{
    var reloadCnt = 0;
    var re = /reloadCnt=(\d+)/;
    var foundReloadParm = false;
    var parms = window.location.search;
    var matches = parms.match(re);
    if (matches && matches.length > 1) {
        foundReloadParm = true;
        reloadCnt = parseInt(matches[1], 10);
    }
    if (reloadCnt < 10) {
        setTimeout(function() {
            var url;
            if (foundReloadParm) {
                url = window.location.href.replace(re, "reloadCnt=" + (reloadCnt + 1));
            } else {
                if (window.location.href.indexOf("?") == -1) {
                    url = window.location.href + "?reloadCnt=1";
                } else {
                    url = window.location.href + "&reloadCnt=1";
                }
            }
            window.location.replace(url);
        }, 10000);
    }
}

Solution 2:

Frankly, argh!

Firstly, don't pass strings into setTimeout, please, it's just awful. Especially when your not even passing any parameters.

Do things like this instead:

setTimeout(refresh,10000);

That way, you are passing a reference to the actual function, not calling eval() by proxy. Douglas Crockford would be turning in his grave (if he was dead).

Nextly, ALL javascript statements should be terminated with a ;, not just lines at random.

Nextly, none of your code will actually do anything after the timeout held in t has fired and window.location.reload() is called. When the page is reloaded, you have essentially been given a new environment with a clean slate, and the process will start over again.

As it stands, you whole code could be abreviated to this:

<html><head></head><bodyonload="setTimeout(window.location.reload,10000)"></body></html>

To fix it you will need to track between browsing sessions. There are a thousand ways you could do this - URL parameters, cookies, iframes and many more. But the simplest of these is probably URL (or GET) parameters, so we will focus on that.

When the page is first loaded, we need to start the tracking by creating an integer value that we can increment as time goes on. Then, on each successive load, we need to check that the current value falls within range and if it does, increment it and pass it to the next iteration.

So you could do something like this...

<html><head><scripttype="text/javascript">var refreshURL; // Declare this globally so we can access it in the function from refreshPage()functionrefreshPage () {
        window.location.href = refreshURL;
      }

      window.onload = function () { // This construct is equivalent to setting an 'onload=' for the body tag// Declare some variablesvar urlBase, urlParams, urlParts, trackerVar, urlBase, queryStr, i, queryParts, paramParts, paramKey, paramVal, j;
        urlParams = {};

        // Parse the URL parameters into an object and get the base URL
        urlParts = window.location.href.split('?');
        urlBase = urlParts[0];
        queryStr = '';
        for (i = 1; i < urlParts.length; i++) {
          if (i > 1) {
            queryStr = queryStr + '?';
          }
          queryStr = queryStr + urlParts[i];
        }
        queryParts = queryStr.split('&');
        for (i = 0; i < queryParts.length; i++) {
          paramParts = queryParts[i].split('=');
          paramKey = paramParts[0];
          paramVal = '';
          for (j = 1; j < paramParts.length; j++) {
            if (j > 1) {
              paramVal = paramVal + '=';
            }
            paramVal = paramVal + paramParts[j];
          }
          urlParams[paramKey] = paramVal;
        }

        if (urlParams['__tracker'] == undefined) {    
          // this is the first load, define the tracker as '1'
          urlParams['__tracker'] = 1;
        } else {
          // this is not the first load, increment the tracker
          urlParams['__tracker'] = parseInt(urlParams['__tracker']) + 1;
        }

        // build the url for the refreshPage function
        refreshURL = urlBase + '?';
        queryStr = '';
        for (i in urlParams) {
          if (i != '' && urlParams.hasOwnProperty(i)) {
            queryStr = queryStr + '&' + i + '=' + urlParams[i];
          }
        }
        refreshURL = refreshURL + queryStr.substr(1);

        if (urlParams['__tracker'] < 6) {
          // If the tracker is less than 6, reload the page in 10 secondssetTimeout(refreshPage,2000);
        }

      };

    </script></head><body></body></html>

I know I was a bit late with this answer, but I think it was worth writing...

Solution 3:

Instead of using window.location.reload(), consider using AJAX to dynamically load the information you need without refreshing the page. As others have pointed out, you can use URL parameters but it's arguably nicer for the user to not have the entire page refresh on them.

Here's a tutorial on AJAX with PHP: http://www.tizag.com/ajaxTutorial/ajaxform.php

Solution 4:

You can pass an arbitrary HTML page parameters. These will not be processed on the server, but on the client.

Then, increment the given parameter, or initialize if none was given. This way you can keep track between page reloads.

Solution 5:

Since you didn't specify any server-side language, I'd suggest the first solution that comes to my mind: put the whole page in one iframe and next to it put your JavaScript code. You can also replace the first setInterval with a setTimeout that will just keep calling the function until you call clearInterval. Finally, you should replace the refresh() function with this:

function refresh ()
{
varif = document.getElementById('iframeid');
if.src = if.src;
}

Your script should be something like this:

<scripttype="text/javascript">var t;
var j;
functionload()
{
t=setInterval("refresh()", 10000);
j=setTimeout("stop()", 60000);
}

functionrefresh ()
{
varif = document.getElementById('iframeid');
if.src = if.src;
}

functionstop(){
clearInterval(t);
}
</script>

Post a Comment for "Stop Javascript Auto Refresh After Fix Time For Example 1 Min"