Ask coding questions

← Back to all posts
Run while off
WilliamXing (45)

@CodingCactus in your cactus clicker, how did you make it run while the user wasn't on the tab?

Answered by InvisibleOne (2674) [earned 5 cycles]
View Answer
CodingCactus (4190)

it isn't running, it just calculates how much time it has been since you last were on the site (using local storage) and then uses that to see how many cacti you would have got in that time : )

WilliamXing (45)

Can you teach me how to do that? @CodingCactus

WilliamXing (45)

I'm not exactly a JS pro, so could you tell me? @CodingCactus

InvisibleOne (2674)

@WilliamXing What he's saying, is to put the current time in local storage.
localStorage.setItem('time', whatever_the_time_is)
Then when you reopen the page, take that time and the current time now. Remove the old time from the new time to tell how much time has passed. Once you know how many seconds have passed, you can easily multiply that by the amount of cacti/points you get per second, then add that to your score.

WilliamXing (45)

How do I make the "Whatever the time is" and the "What time is it when the user opens it"? And, how do I do the subtraction? @InvisibleOne

InvisibleOne (2674)


Whatever the time is

var myTime = new Date.getTime();

Saving that to local storage

localStorage.setItem('time', myTime);

Then getting that value

oldTime = +localStorage.getItem('time')


2 - 1 // will give us 1

With the time

currentTime = new Date.getTime();

timePassed = currentTime - oldTime;
InvisibleOne (2674)

If the tab is open it should be running, it should only stop if you close the tab

2plus2is4hoi (94)

do ctrl + u in the tab and you can see the source code