Eldon Lesley
Eldon Lesley

Reputation: 925

Long-running JavaScript Web

I am making a website that contains html5 and JavaScript, The website requires very few user interactions (only at the start), after that the web will display all kind of informations (text, time, pictures, etc)

In the website I always use timer (setInterval) at specified intervals (3seconds or even 20seconds), For the first 2 hours, it runs fine, after that, sometimes it will crash the browser or make it hang, Now I wonder if using setInterval is a good idea

I always clear the interval (with clearInterval) if I want to change the interval then activate it again. I need the web to run days or even weeks, sometimes if it's not hang, it will cause the browser(not the whole PC) to run very slow,

so is it actually a good idea to use setInterval and clearInterval in the long run? Or should I switch to setTimeout instead (or will they be the same)?

If the cause is memory leak, could this be the cause?

var element=document.getElementById("image1"); //it is DIV element
var image=new Image(); 
image.src=url;  // url is a path to a specific image(blob or external source)
image.onload=function(){
//basically
element.style.backgroundImage = "url(" + url + ")";
element.style.width=image.width.toString()+"px"; //set the original size
element.style.height=image.height.toString()+"px";
 //by the end of this function I don't clear the variable image like image=null
};

Upvotes: 1

Views: 117

Answers (2)

Eldon Lesley
Eldon Lesley

Reputation: 925

I found it! Apparently it was not because of the image and DOM creation as I was always handle them correctly after a closure, It was because after some changing of certain DOM Element, I always attach event-handler to an object with jquery ($(element).bind(eventhandler,theHandler);)

I thought when I attach the event with bind, it will replace the handler, but apparently it will stack all og the handlers attached with the new one. So now, I do it only once or unbind the old one if necessary

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

Afaik there shouldn't be any problems with setInterval, but i guess that you have a memory leak in your source code:

Check this thread to find tools to help you debug

Does this go to the GC?

var a = {}; 
var b = {a: a}; 
a.b = b;

Or this:

var a = function(b) { 
    var c = function(b) {}; 
    c(b); 
}
var b = {}; // <-- what about this object?
a(b); 

Maybe you should start rethinking if its a good idea to have a browser running for multiply weeks maybe you should start looking at nodejs?

Upvotes: 0

Related Questions