Reputation: 29
So i have a major function
which triggers another function
every 2 - 17 seconds but when I try to stop it with clearTimeout()
it just goes on and completely ignores the clearTimeout()
.
So this is my major function:
var itemTimer;
var stopTimeout;
function major (){
var itemTime = Math.floor(Math.random() * 15000) + 2000;
itemTimer = setTimeout('items()', itemTime);
stopTimeout = setTimeout('major()',itemTime);
}
And this is my stop timeout function:
function stopTimer() {
clearTimeout(itemTimer);
clearTimeout(stopTimeout);
}
Thank you for helping
Upvotes: 0
Views: 67
Reputation: 7916
I think your timeouts are stacking up. As soon as major
gets called once, the variables itemTimer
and stopTimeout
get reassigned a new timeout reference. So there will be no way to clear the timeouts that were previously set. If this is the case it should be an easy fix though. Just call stopTimer
as very first statement in major
:
function major (){
stopTimer();
var itemTime = Math.floor(Math.random() * 15000) + 2000;
itemTimer = setTimeout('items()', itemTime);
stopTimeout = setTimeout('major()',itemTime);
}
Upvotes: 1
Reputation: 42354
Your setTimeout()
is being called incorrectly; you're invoking items()
and major()
. Instead, you need to pass them as functions to be invoked.
Don't pass the brackets to the parameters, and don't wrap the parameters in quote marks.
Instead of:
itemTimer = setTimeout('items()', itemTime);
stopTimeout = setTimeout('major()',itemTime);
You're looking for:
itemTimer = setTimeout(items, itemTime);
stopTimeout = setTimeout(major, itemTime);
Hope this helps! :)
Upvotes: 1