简体   繁体   中英

Javascript setInterval() executing twice at the same time

I am having a problem where I have a single setInterval() but it's executing twice at the same time. My code clones a image from one div and places it in another one. The setInterval() is cloning 3 times the image but in reality it clones 6 times. I have an alert when the setInterval ends. The alert pops out when the 5th clone is placed and again with the 6th clone, which means that the 5th clone is the end of the first setInterval() and the 6th is the end of the second one. But I want only 1 setInterval() that makes 3 clones. What is happening?

HTML:

<div class="inimigo">
     <img src="inimigo.png">
</div>

<div class="jogo2">

</div>

jQuery:

$(document).ready(function() {
    var counter2 = 0;
    var i = setInterval(function() {
        var inimigo = $(".inimigo").clone();
        $('.jogo2').html(inimigo);

        counter2++;
        if(counter2 === 3){
            alert("end");
            clearInterval(i);
            counter2 = 0;
        }
    }, 200);
});

I guess Clone is causing issue. When you use html() you should pass HTML as text.

Please check solution, ( JSFiddle )

$(document).ready(function() {
    var counter2 = 0;
    var i = setInterval(function() {
        var inimigo = $(".inimigo").clone();

        // Followin is the fix code
        $('.jogo2').prepend(inimigo.html());
                // or use append to put new content at last
        //$('.jogo2').append(inimigo.html());

        counter2++;
        if(counter2 === 3){
            alert("end");
            clearInterval(i);
            counter2 = 0;
        }
    }, 200);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM