naresh kumar
naresh kumar

Reputation: 2241

Removing the setTimeout interval

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);

Upvotes: 1

Views: 267

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382194

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);
    }

Upvotes: 1

Varada
Varada

Reputation: 17052

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

Upvotes: 0

Related Questions