简体   繁体   English

Javascript setInterval()同时执行两次

[英]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. 我有一个问题,我只有一个setInterval()但它同时执行两次。 My code clones a image from one div and places it in another one. 我的代码从一个div复制一个图像,然后将其放置在另一个div中。 The setInterval() is cloning 3 times the image but in reality it clones 6 times. setInterval()会克隆图像的3倍,但实际上它会克隆6次。 I have an alert when the setInterval ends. setInterval结束时,我有一个警报。 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. 放置第5个克隆时,会弹出警报,并再次放置第6个克隆,这意味着第5个克隆是第一个setInterval()的结尾,而第6个是第二个setInterval()的结尾。 But I want only 1 setInterval() that makes 3 clones. 但是我只需要1个setInterval()进行3个克隆。 What is happening? 怎么了?

HTML: HTML:

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

<div class="jogo2">

</div>

jQuery: 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. 使用html() ,应将HTML作为文本传递。

Please check solution, ( JSFiddle ) 请检查解决方案,( 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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