Hi, I have a setInterval which executes its command every 10 seconds in
a infinite loop.
I've got something real basic like:
var processes=0;
function startme(){
if(stopthisloop>1)
Where is stopthisloop defined or set?
Where is loop defined or set?
setTimeout('runthiseverytenseconds()', 10000);
setTimeout and setInterval return a reference to the object that will
run later, you can use that referecnce with clearTimeout() to stop the
object from executing.
That function will call 'runthiseverytenseconds' once after about 10
seconds have elapsed. I'll guess that your 'runthiseverytenseconds' is
using a loop to call startme and that loop is creating thousands of
setTimout objects that suck up all available CPU.
It works but is a massive CPU hog. I guess there is a better way. How
can I do this? I do need to be able to start & stop it, so if you can
show me how that would be so nice.
Here's an example, once you get close to what you want you may need to
ask here again.
<script type="text/javascript">
// Global to hold reference to Timer - some other scheme
// would be better
var x;
// Constructor for a Timer object that runs fn at interval lag
// using apply and extra arguments supplied
function Timer(fn, lag, args){
this.fn = fn;
this.lag = lag;
this.args = [];
for (var i=2, len=arguments.length; i<len; i++){
this.args.push(arguments
);
}
this.timerRef;
}
// A method to start the Timer
Timer.prototype.start = function(){
var fn = this.fn;
var args = this.args;
this.timerRef = setInterval(function(){
fn.apply(window, args);
}, this.lag);
}
// A method to stop the Timer
Timer.prototype.stop = function(){
if (this.timerRef) clearTimeout(this.timerRef);
}
// A simple function to run, requires two args -
// an element to update and an increment
function counter(el, num){
if (typeof el == 'string') el = document.getElementById(el);
el.firstChild.data = +el.firstChild.data + +num;
}
</script>
<div id="counterText">0</div>
<!-- When starting the Timer, see if it's already running and if
so, stop it (or just return and do nothing) -->
<button onclick="
if (x && x.stop) x.stop();
x = new Timer(counter, 500, 'counterText', 5);
x.start();
">Start counter</button>
<!-- When stopping the Timer, make sure it's already running
before trying to stop it -->
<button onclick="
if (x && x.stop) x.stop();
x = null;
">Stop counter</button>