How to loop animation in JavaScript?

  • 0
    I decided to make a Space Invaders game in JavaScript.
    The essence of the question is:
    wrote the code, but it does not work as I would like (the invaders block should move from left to right smoothly, but it blinks, disappears, and generally behaves inappropriately if you increase its speed or increase the frequency of function calls)
    the code itself is here:
    let timer;
    let direction = 'left';
    function moving() {
    
     	if(direction == 'left'){
     		let start = Date.now();
    
          	timer = setInterval(function() {
            let timePassed = Date.now() - start;
    
            invaders.style.marginLeft = timePassed / 4 + 'px';
    
            if (invaders.style.marginLeft.slice(0,invaders.style.marginLeft.indexOf('p')-1) > 670) {clearInterval(timer); direction = 'right'};
    
          }, 20);
     	}
     	else{
     		start = Date.now();
    
           	timer = setInterval(function() {
            let timePassed = Date.now() - start;
    
            invaders.style.marginLeft = (685 - timePassed / 4) + 'px';
    
            if (invaders.style.marginLeft.slice(0,invaders.style.marginLeft.indexOf('p')-1) < 10) {clearInterval(timer); direction = 'left'};
    
          }, 20);
          }
          	}
    
          window.onload = setInterval(moving, 3000);

    I had an idea like this: create a function that moves left and right, depending on the variable (in the future it will all be a method and object property), the function is called cyclically (or the function itself is infinite) when it is necessary to change the direction (width the block inside which the movement will be equal to 670-680, that is, do not go beyond these limits)
    I'm not sure if I'm thinking in the right direction, that's why I created this question here, if there are better ideas or ideas for improving the existing code - write them here, please.
    JavaScript Anonymous, May 10, 2019

  • 1 Answers
  • 0
    Wildly blunt, everything can be implemented much easier:

    let direction = 'left';
    let invaders = document.getElementById("invaders");
    let i = 0;
    function move() {
    if(i > 677) {
    direction = 'right'
    }

    else if (i < 5){
    direction = 'left'
    }

    if(direction == 'left'){
    invaders.style.left = i + 'px';
    i++;
    }

    else if(direction == 'right'){
    invaders.style.left = i + 'px';
    i--;
    }

    }
    window.onload = setInterval(move, 10)
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!