this specific portion of code else if (left <= 200)
doesn't make sense at all
here's a more efficient way to achieve the same result:
const element = document.querySelector('.element');
element.textContent = 'hahahaha';
element.style.position = 'absolute';
element.animation = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 }
setInterval(() =>
{
element.animation.pos += element.animation.step
if (element.animation.pos >= element.animation.max) element.animation.step = element.animation.stepBack
if (element.animation.pos <= element.animation.min) element.animation.step = element.animation.stepOn
element.style.left = `${element.animation.pos}px`
}, 10)
* {
padding : 0;
margin : 0;
}
<div class="element"></div>
You can also utilize requestAnimationFrame() for smoother animations
const element = document.querySelector('.element')
element.textContent = 'hahahaha';
element.style.position = 'absolute';
element.animation = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 }
function moveElement()
{
element.animation.pos += element.animation.step
if (element.animation.pos >= element.animation.max) element.animation.step = element.animation.stepBack
if (element.animation.pos <= element.animation.min) element.animation.step = element.animation.stepOn
element.style.left = `${element.animation.pos}px`
requestAnimationFrame(moveElement)
}
requestAnimationFrame(moveElement)
*{
padding: 0;
margin: 0;
}
<div class="element"></div>