简体   繁体   中英

Javascript animation with setInterval doesn't work

I'm creating a simple animation with a comet goes down.

Here is the comet itself:

var cometScene = function(){
    var b = document.createElement('div');
    b.id = 'cometio';


    var cometImage = document.createElement('img');

    cometImage.setAttribute('src', 'images/comet1.png');
    b.appendChild(cometImage);

    document.getElementById('wrap').appendChild(b);
}

And here is the move:

function cometMove(){
    var comet = document.getElementById('cometio');
    var pos = 0;
    var interval = setInterval(scene, 3);

    function scene(){
        if (pos === 1000){
            clearInterval(interval);
        } else {
            pos++;
            comet.style.top = pos + 'px';
            comet.style.left = pos + 'px';
        }
    }
}

But the problem is it is only happens once and then I have to refresh the page to run an animation again. What am I doing wrong here?

I have to refresh the page to run an animation again

if (pos === 1000){
   clearInterval(interval); /* you have stopped animation here */
}

To re-run or keep running, possibly you may just reset the position of comet:

if (pos === 1000){
   pos = 0;
}

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