0

I created a little timer which runs from 30seconds down to 0 and saved in the localStorage, butthen restarts after a event and again begins at 30secs. But if I open 2 tabs of the same page the code runs double. That means that after 1 seconds the timer jumps for example from 30 to 28.

    function timer(){
    localStorage.setItem("time", 30);
    
    setInterval(function(){
        localStorage.setItem("time", localStorage.getItem("time") - 1);
        timerPlace.innerHTML = localStorage.getItem("time");
        if(localStorage.getItem("time") < 0){
            localStorage.setItem("time", 0); 
            timerPlace.innerHTML = "TIME TO PLACE !";
        }
    }, 1000);
    
    
    if(localStorage.getItem("time") === null){
        localStorage.setItem("time", 30);
    }
    
}

I already thought of getting the number of opened tabs and do something with this. Or maybe there is a way to only run a javascript code in one tab.

7
  • 1
    localStorage is per origin (the website url) not per tab, so one tab is setting localStorage to one number and the other is setting it to another nummber. Commented Sep 21, 2022 at 15:28
  • 1
    the script could append some time based string to the index and constantly reference that throughout the function, each tab would have its own timer Commented Sep 21, 2022 at 15:29
  • If the data only needs to persist for the session you may be able to use session storage instead, as this is not shared between tabs. Should be an easy replacement as all the available methods on local storage are also available in session storage. Commented Sep 21, 2022 at 15:30
  • But does session storage save this local for every tab Commented Sep 21, 2022 at 15:34
  • Every tab should have the same time Commented Sep 21, 2022 at 15:35

1 Answer 1

2

Store the start time of your count in localStorage. Then calculate the distance from it in seconds. when reach 30, clear that value.

This example is without using localStorage because not allowed in a stack snippet.

var start = (new Date()).getTime();
var ind_id
ind_id = setInterval(function() {
  var now = (new Date()).getTime()
  var diff_in_seconds = Math.round((now - start) / 1000)
  if (diff_in_seconds >= 30) {
    cancelInterval(ind_id)
    return;
  }
  timerPlace.innerHTML = (30 - diff_in_seconds)
}, 1000)
<div id="timerPlace"></div.>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.