Alina Khachatrian
Alina Khachatrian

Reputation: 757

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?

Upvotes: 0

Views: 48

Answers (1)

user2575725
user2575725

Reputation:

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;
}

Upvotes: 1

Related Questions