Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep timer (setInterval) running while reloading page

Tags:

javascript

Once I load a webpage, I insert some Javscript via the console. I was wondering if it's possible for me to, using either Javascript or jQuery, reload the page (not from cache) while keeping a setInterval that I have running. I'm familiar with location.reload(), but that terminates it.

like image 366
Ryan Lucia Avatar asked Apr 12 '14 22:04

Ryan Lucia


People also ask

Does setInterval execute immediately?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

Does setInterval repeat?

Yes, setInterval repeats until you call clearInterval with the interval to stop. By way of example, the following code will count to 5. setInterval sets up the counter, setTimeout sets up a single event in 5 seconds to stop the counter, and clearInterval stop counting.

Does setInterval affect performance?

This is unlikely to make much of a difference though, and as has been mentioned, using setInterval with long intervals (a second is big, 4ms is small) is unlikely to have any major effects.


1 Answers

When you reload a page, the entire page context including all running JS is completely destroyed. You cannot keep a setInterval() running while its host page is reloaded.

You can create a signal for the new page to start the interval going again itself using a cookie, query parameter or local storage value (query parameter is probably the most appropriate). If you go this way, then you need to code the page to look for a specific query parameter and if it finds it, then the page should start the designated setInterval() itself. You can even pass some data in the query parameter (such as how much more time until the next interval should fire, etc...).

Another option is to not actually reload the page, but instead to refresh the content manually by getting new content via an ajax call and then inserting it into the current page. This allowed the current page context and running interval timers to continue running.

like image 67
jfriend00 Avatar answered Oct 19 '22 04:10

jfriend00