JUNSKI
JUNSKI

Reputation: 1

Fixing double running of javascript code in different tabs

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.

Upvotes: 0

Views: 78

Answers (1)

IT goldman
IT goldman

Reputation: 19485

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.>

Upvotes: 2

Related Questions