0

I have a javascript timer in my page to submit a form if the seconds=0.It is working fine.But the problem is, on refreshing the page,the timer is starting from initial value.

Here is the javascript code

<script>
    secs = 300;
    timer = setInterval(function () {
        var element = document.getElementById("status");
        element.innerHTML = "Remaining :<b>"+secs+" sec</b>";
        if(secs < 1){
            clearInterval(timer);
            document.test.submit();
        }
        secs--;
    }, 1000);

Is there any way to avoid this? It can be achieved by preventing page reload. Is that possible?

Hari
  • 43
  • 8
  • if you want to make it persistant , you can use localStorage or some other type storage accordingly , on page refresh all values will get refreshed – Ahtisham Jun 17 '16 at 11:25
  • you can find more information related to preventing page reload here -http://stackoverflow.com/questions/3527041/prevent-any-form-of-page-refresh-using-jquery-javascript – Ahtisham Jun 17 '16 at 11:26

2 Answers2

1

You could submit the current timer value as part of the form post (for example by dynamically adding a hidden form element before submit), and then use this value as the initial value for the timer after the page reload.

Another possibility would be to submit the form using AJAX so that a page refresh is not required. To achieve this you could look into the jQuery ajax function: http://api.jquery.com/jquery.ajax/

I can provide an example if one of these solutions sounds okay.

Milney
  • 6,253
  • 2
  • 19
  • 33
0

All the variable are reinitiated on page load.if you want to retain some value , you will have to use the window.sessionStorage.

https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage

Deep
  • 9,594
  • 2
  • 21
  • 33