Daniel
Daniel

Reputation: 101

window.setTimeout() Troubles

I'm having some trouble with an image loading before other code is executed. I have a work around by setting a timer that will run for a fraction of a second which will let the image load before other code is executed. I tried to repeat the work around, and that just made the page lag out when the dealer hits.

My files would make this post very lengthy, so I'll just give links to the github repo.

Git HTML Preview

For the complete code, please see the JS File

first instance of workaround (hit(): line 30) (this works)

window.setTimeout(function afterHit(){
    if(count(playerCards) == 21){
        stand();
    }
    else if(checkBust(count(playerCards))){
        alert("BUST!");
        clear();
    }
}, 150);

The Part that I'm having trouble with (lines 173 - 183):

function dealerAI() {
    while (count(dealerCards) < 16){
        window.setTimeout(function dealerHit(){
            console.log("check count");
            var i = dealerCards.length;
            dealerCards[ i ] = drawCard();
            document.getElementById( "dealer-cards" ).innerHTML += "<img src='src/img/" + dealerCards[ i ][ 1 ].toString().toLowerCase() + "-" + dealerCards[ i ][ 0 ] + ".png' />";
        },500);
    }
    window.setTimeout(checkWin,500);
}

If I do this, it works kind of the way I want it to, but I want the dealers moves to be slower so that the player can see what the dealer is doing. It's really only a problem when the dealer has to hit more than once.

function dealerAI() {
    while (count(dealerCards) < 16){
        console.log("check count");
        afterAIHit();
    }
    window.setTimeout(checkWin,200);
}
function afterAIHit(){
    window.setTimeout(dealerHit(),200);
    }
function dealerHit() {
    var i = dealerCards.length;
    dealerCards[ i ] = drawCard();
    console.log(dealerCards[i]);
    document.getElementById( "dealer-cards" ).innerHTML += "<img src='src/img/" + dealerCards[ i ][ 1 ].toString().toLowerCase() + "-" + dealerCards[ i ][ 0 ] + ".png' />";
}

Any help would be appreciated :)

Thanks!

Upvotes: 0

Views: 102

Answers (1)

JJJ
JJJ

Reputation: 3332

Since you're waiting for an image to load to process your script, just attach an event listener that will process your code after the image has loaded.

document.querySelector ("#imageWaitingFor").addEventListener ("load",function (){
//Your code
});

Upvotes: 1

Related Questions