http://jsfiddle.net/mplungjan/SyHFR/
Sorry for the messy code - I have modified a script not chosen by me and originally from Dynamic Drive - it is used by someone I am helping and rather that rewriting the whole thing from scratch, I agreed to the feature creep. The intended changes was to add a repeat after and a delay by vars
Now I just want to understand where there could be a problem - I changed the code from using a date object every second to use i开发者_如何学编程t only when initialising.
The code
cdtime.prototype.updateTime=function(){
var thisobj=this;
this.currentTime+=1000; // one second
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}
gives a
Message: 'thisobj' is null or not an object
after about 9 hours in IE8 on XP
I am running it myself now on another box over the weekend, but was wondering if someone could enlighten me as to what could be the issue with IE.
HMM - pasting the function right now, I see the settimeout is inside a prototype - that suddenly does not look right.
Please also do feel free to point me to a better counter that can do what this one is doing, e.g. start after a delay, repeat after a given time and have more than one counter on the page styled by CSS.
UPDATE
Trying the setInterval makes the whole coundown very choppy http://jsfiddle.net/mplungjan/z2AQF/
If it is really a memory leak, try clearing the thisobj
variable from the function passed to setTimeout
:
cdtime.prototype.updateTime = function () {
var thisobj=this;
this.currentTime+=1000; // one second
setTimeout(function () {
thisobj.updateTime();
thisobj = null;
}, 1000); //update time every second
};
If you look closer, this function is basically an interval, so the following would be more optimized since it does not stack up on old functions:
cdtime.prototype.updateTime = function () {
var thisobj = this;
setInterval(function () {
thisobj.currentTime += 1000;
}, 1000);
};
精彩评论