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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With