1

On one page of my site, timers are created. I need to be able to access those timers on other pages to see the time left. But I can't get the global array to work properly.

In the head of the site I create the all_timers array if it is empty. Then in my timer function I push the id of the timer onto that array. But when I reload the page the array is always empty.

When the timers page is ran, the console shows "pushed". But whenever the page is updated, it shows "create new".

I'm confused by the use of window. Some posts said to use it, some don't mention it and some show it is used for all instances of the variable, not just when it is created. Sp am I creating the global incorrectly? I just show the basic use here, though I tried many variations. Would someone please point out what I am missing? Please note that this is stripped-down code. The timer function does actually get called.

    <head>

    <script> 
    if (typeof all_timers !== 'undefined' && all_timers.length > 0) {
      console.log('found '+all_timers.length);
      for (var i = 0; i < all_timers.length; i++) {
        console.log('main timer '+all_timers[i]);
      }    
    } else {
      console.log('create new');
      window.all_timers = new Array();
    }
    </script>

    </head>
    <body>


    <script>
    function createfunc(idx) {
        if ($("#time-left-"+idx).length === 0) {
          clearInterval(timerID[idx]);
        } else { 
          timerID[idx] = setInterval(function() {
            if (show_timer > 0) {
              all_timers.push('some thing'+idx);
              console.log('pushed');
            } else {
              clearInterval(timerID[idx]);
            }   
          }, 1000);
        }    
    }
    </script>
    </body>
user3052443
  • 758
  • 1
  • 7
  • 22
  • 6
    When a new page is loaded, *everything* from the previous page will be gone (except `localStorage` and `sessionStorage`). – Pointy Jun 21 '19 at 17:45

1 Answers1

2

You will need to either save the global timestamp with local storage or pass the timestamp as a URL parameter.

Whether you use local storage or url parameters you will only be able to pass a string between pages.

nachshon f
  • 3,540
  • 7
  • 35
  • 67