I am currently exploring the world of animation in JavaScript and I have a few practical questions. In my script, I am attempting to "launch" a "rocket" upon clicking a "button". What I've observed is that although my function calculates values as intended, the rocket's position on the webpage does not change until the function completes.
Here are my questions:
Is there a way to dynamically update the location (rocket.style.top) of the rocket within my function? If not, what would be a more effective approach to updating the location? Should I consider alternatives to using an event listener on a button?
var button = document.querySelector('.button');
var rocket = document.querySelector('.rocket');
var x = rocket.offsetTop;
var a = 1;
function launch() {
while (a < 1000) {
console.log(x);
console.log(a);
console.log(rocket.style.top);
rocket.style.top = x - a + 'px';
a += a;
sleep(1000);
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
button.addEventListener('click', launch);
div.button {
font-family: impact;
letter-spacing: 1px;
text-transform: uppercase;
margin: auto;
text-align: center;
background-color: rgba(255, 0, 0, 1);
border-style: solid;
border-width: 1px;
border-radius: 100px;
width: 75px;
height: 25px;
padding: 25px 0;
cursor: pointer;
}
div.rocket {
position: absolute;
background-color: rgba(0, 0, 0, .5);
width: 25px;
height: 25px;
bottom: 0%;
left: 5%;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class='button'>launch</div>
<div class='rocket'></div>
</body>
</html>