Search code examples
javascriptfunctionsettimeoutcleartimeout

I somehow can't stop my setTimeout() loop


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


Solution

  • 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! :)