user1238321
user1238321

Reputation: 249

settimeout being ignore, function is called instantly

 function ShowColoursScreen() {
    setSquaresList()
    $("#ModeOne").hide();
    $("#ModeTwo").show();
    setTimeout(function () {
        $("#ModeOne").show();
        $("#ModeTwo").hide();
        setTimeout(function () {
            ShowColoursScreen();
        }, 1500);

    }, 15000);
}

This is very very weird, Im wanting to rotated between two divs every 15 seconds (i dont want to use js intervals). However after the first fifteen seconds ShowColoursScreen(); runs without waiting the second 15 seconds (if that makes sense). Its like the timeout gets ignored, any ideas?

Upvotes: 0

Views: 258

Answers (2)

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

function ShowColoursScreen($elements) {
    if(!$elements instanceof jQuery) {
       $elements = $($elements);        
    }

    var current = 0;
    // What does this function do?
    setSquaresList();

    function showCurrent () {
       var $currentElement = $($elements[current]);
       $elements.not($currentElement).hide();
       $currentElement.show();
       (current++) % $elements.length;
       setTimeout(showCurrent, 15000);
    }
    showCurrent();
    return $elements;
}

ShowColoursScreen('#ModeOne, #ModeTwo')

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

Your code is correct. However, the inner timeout just waits for 1.5 seconds as you forgot a zero. Simply replace the 1500 with 15000.

You can also simplify the call a bit - as you do not have any arguments there is no need for the anonymous function: setTimeout(ShowColoursScreen, 15000);

Upvotes: 2

Related Questions