It may be a naive question but I need to know the answer.
This is my code,
setInterval(function() { /do stth./}, 1000);
I never cancel the timer, I need to run it as long as user is on the page, I need to know will it case any memory leak, or when will it stop (ie, browser refresh, browser close)?
The only problem can occur when you "do something". If you have other long running functions or even additional intervals inside the interval (a la Javascript Inception) then you could run into performace issues.
However, in almost all cases, you won't have any problems.
When the user refreshes the browser, the interval will begin anew. When the browser is closed then all activity stops.
As long as the user doesn't refresh the browser or leave the page then the interval will never end.
it stops when you leave the page. It shouldn't cause leaks.
Related
I've got a simple timer that I built that works off of a setInterval function. Every 1 second, it increases the value of the timer by 1. When I click off of the tab to a different tab in Safari, it slows down. You can see what I'm talking about in this basic CodePen:
http://codepen.io/anon/pen/rxVMRp
This is the basic JS code:
function setTimer(){
var curTime = parseInt($('.timer').text());
var newTime = curTime+1;
$('.timer').text(newTime);
}
setInterval(setTimer, 1000);
Granted, my timer is a bit more advanced, but you can still see the slow down effect of setInterval in Safari in this basic example. How can I prevent this slow down without having to offload anything to a web worker?
Is there any particular reason you're using a setInterval here? Probably the reason Safari is slowing down on blur is to prevent tabs from wasting CPU cycles when the user isn't paying attention to them. What could possibly be so important in your code that it needs to be updated every second, even when the user isn't focused on it?
At any rate, you could listen for onblur and onfocus to pause or restart the timer as necessary. If you need to keep perfect timekeeping for some other purpose there is always Date.now().
Using JavaScript (and/or jQuery), Is it possible to pause the user from exiting a page for a set amount of time without showing an alert/confirmation?
(Say the user clicks on a different page or closes the window, a timer should start for three seconds [during which time something happens] and then the next page is loaded or the window closes.)
No, it is impossible in modern browsers.
(Moreover, think of how annoying that would be if every popup did that)
The closest you can do is show the dialog using onbeforeunload but you have asked to avoid this.
But why would you want to do that?
Worth mentioning, that this is a magical time. You might want to report something to the server but you suddenly can't because the user is leaving. This is one of those times things that are usually considered bad practice like synchronous ajax might make sense.
No. This is not possible. At best you can implement an onbeforeunload handler but your options at this point are very limited (you can certainly not 'wait 3 seconds').
Browsers will try to protect the user so this is behavior that browsers enforce and they have incentive to enforce it.
This works in chrome and firefox:
window.onbeforeunload = function() {
var now = new Date();
while( new Date() - now < 3000 );
};
It will also drain battery, so you are killing 2 birds with one stone.
I've got a page that shows real-time statistics. It runs a lot of javascript, makes a lot of HTTP requests, renders SVG charts every few seconds using D3.js, has a lot of CSS animations, and rearranges the DOM frequently.
As long as the page is focused, it runs smoothly. If I switch to another tab and come back later, there's often a short pause where the page seems to be frozen before the view suddenly seems to rerender and the page becomes usable again. The longer the tab has been backgrounded, the longer this pause is. If the tab has been in the background for a very long time (hours) and I switch back to it, it will be frozen for a long time then crash.
All these behaviors are observed in Chrome. I haven't tested much in other browsers.
What is Chrome doing during that pause when I first switch back to the tab?
You're running a setInterval or a series of setTimeouts.
Each one is queued up to run AFTER the point you specify in the function.
Google throttles everything on your page down to a few updates every second...
...so if you've got timers set to move things around and animate at 30fps or whatever, then you've got Google firing one round of updates (whatever you have scheduled), which will undoubtedly call something requesting another update, which will request another one...
...when you switch back, you've got hundreds (or tens of thousands) of these updates waiting to happen, and now instead of happening at 30fps, you have a bunch of these things waiting... all of them have passed their "do not run until..." time, and they're all going to try to update as fast as physically possible, until you get caught up to where the timer is current again.
If the browser supports the components of the page-visibility API, then pause your calls when the page is not visible.
if (!document.hidden) { doStuff(); }
OR
document.addEventListener("visibilitychange", function (evt) {
if (evt.visibilityState === "hidden") { myApp.pause(); }
else if (evt.visibilityState === "visible") { myApp.resume(); }
});
If it doesn't support the API, then you can try to polyfill it, using window.onblur, or otherwise.
That said, chances are if the browser doesn't support the page-visibility API, it also doesn't do hardcore throttling of the page-code.
That's not a 100% guarantee, but rather a semi-likelihood.
I have this functionality built in Jquery/ javascript where a user is notified when their session is about to be timed out. Then they are given an option to extend it. If they don't make a choice the pop up closes itself and the browser is redirected to the login page. It worked perfectly fine for a while. But now I noticed it works correctly only if I am active on the computer. If the computer is left unattended for an entire day, the pop up does not begin the countdown until the user unlocks the computer and logs in again.
Is anybody aware of this behavior where ie stops executing javascript when the computer is left unattended for a long time?
Update: Is there a way to keep the tab from sleeping? Without that, the browser won't be able to redirect at the right time.
setTimeout only works when the tab is active. In some browsers even changing tab will make it stop counting. So not only if you are on the computer but if you're not on the specific page it might not work. Also on mobile devices with multitasking it's bound to fail, forget about tabs, applications often go to suspended mode.
Take a look at this question, it offers the same solution as Luka with a code example:
How can I make setInterval also work when a tab is inactive in Chrome?
You might want to do two checks on the time passed, one to check if you need to show the popup, and one to close the popup, using the total time passed instead of having a different count down.
i would suggest logging the current time when the page is loaded and then calling a function every 10 seconds of so that checks if the time passed is more than x amount, the reason your problem occurs is most likely because the default timeout function only counts down while the page is being rendered.
I am writing a Google Chrome extension. Thanks to everyone here for putting up with my silly-assed questions. The routine is primitive but runs fine. The only problem is that it runs so fast that it overloads the server and my ip address gets blocked. So it needs a throttle.
The question is whether it is better to construct something with a timer or with setInterval. After examining a particular page, the content script closes its window with self.close(). If I put this into a setInterval, I could delay the closing of the page and this would slow the whole process as much as the length of the interval. Seems like a good throttle.
Now the last line of the content script is simply:
self.close();
I presume that if I modify the code as follows I would get my delay:
var t=setTimeout("self.close()",2000);
Will this work? Is there a better way to do it?
I'd rather use :
setTimeout(function(){
self.close();
},2000);
But your way is valid too...
If the closing of the page is an appropriate point to wait, then this is perfectly fine. In this case, because it would appear to be a relevant place, then I think you are fine. Although I would use Christophes suggestion.
Using a setinterval to run them periodically will run into problems if your processing takes longer than the interval - as this seems to involve opening and closing pages, it could.
As a rule, setInterval is good for doing small processes regularly. In this case, you just want to put a wait into the processing, which suggests to me that setTimeout is better.