0

I need to display playing cards when a button is pushed. It should display one card every three seconds. I used a setTimeout for it, but it is not pausing in between. Besides not pausing, the code works perfectly.

<code>function diamonds() {
             for (i = 0; i < deck.length; i++) {
                if (deck[i].suit == "Diamonds") {
               setTimeout(showCard(), 3000);
                }
        }
    }
    function showCard(){
        var $d = $("<div>");
        $d.addClass("current_hand")
            .appendTo("#my_hand");
        var c = deck[i];
        $("<img>").attr('alt', c.name + ' of ' + c.suit )
            .attr('title', c.name + ' of ' + c.suit )
            .attr('src', 'images/cards/' + c.suit + '/' + c.name + '.jpg' )
            .appendTo($d)
            .fadeOut('slow')
            .fadeIn('slow');
        }</code>

From what I can tell, when the function diamonds is called, it should run through an array I have set up, and for each card with the suit of diamonds, it runs the showcard function after 3000ms (3 seconds). It does everything the way it should except there is no pause between cards.

If I am not using the setTimeout method correctly, what would you recommend?

Randall Wolff
  • 7
  • 1
  • 1
  • 4
  • Write `setTimeout(showCard, 3000);` instead. Just `showCard` function name, without execution. – dhilt Oct 22 '17 at 20:25
  • @dhilt That's true, but it still won't cause the effect the OP wants because callbacks to `setTimeout` are placed in the event loop until the JS runtime is isdle. The full loop will be carried out and then the event loop will be consulted. – Scott Marcus Oct 22 '17 at 20:26
  • @ScottMarcus agree... so let me try to write an answer – dhilt Oct 22 '17 at 20:28
  • I took out the (), but then it doesn't execute at all. – Randall Wolff Oct 22 '17 at 20:34
  • @dhilt No need since this is a duplicate. – Scott Marcus Oct 22 '17 at 20:38
  • @dhilt Could you point me to a question that answers it? I'm still pretty new to javascript, and while I don't doubt it has been answered, I was not able to find one with my limited understanding. – Randall Wolff Oct 22 '17 at 20:39
  • @RandallWolff One of possible solutions here is to increase delay time per each new iteration: https://stackoverflow.com/a/5226335/3211932 – `i * 3000` (do not forget to closure `i` variable) – dhilt Oct 22 '17 at 20:43
  • Another option is to build a recursion: https://stackoverflow.com/a/27443296/3211932 – this one is better I think. – dhilt Oct 22 '17 at 20:48

0 Answers0