Search code examples
jquerytimerbrowser-tab

Stop Jquery timer from triggering twice on multiple browser pages


I'm working on a small game in Jquery in my spare time to learn Jquery. The basic concept adds a points everytime the timer ticks and updates the score which is stored in a cookie. This is the timer that handles most off the updates:

setInterval(mainTimer, 1000); //set timer
function mainTimer(){
    createPage(); //updates the page variables and shows the score
    addValues(); //increases the values

}

The problem I'm having is that people could simply open multiple pages and the timer would trigger for each one of those pages. So if you have 4 pages open, the score will get updated 4 times as fast.

I've googled a ton of different things but I can't find anything that works out. A way to do it would be a token some how I'm guessing but I honestly don't know where to start so any help is appreciated.

I read something about the open.window function to check for existing windows but I couldn't anything concrete.

open.window("foo","bar"); 

Solution

  • You could store timestamps and previous values inside the cookie as well, and check for matches there before updating them. So on the interval, you check if the current timestamp is at least 1000ms after the last one. If it is, you update the score and timestamp, if it's not, you give out an error.

    That said, any javascript game without server side validation is prone to 'hacking'.