Reputation: 81
I am trying to slow down an animation of a picture shrinking so that you can actually see it shrink instead of just jump to a smaller size, but what instead happens is that my console log updates as it should-with intervals in-between each update, but the image on the screen waits until the for loop is done and then jumps to the end size instead of gradually getting smaller. Is there something wrong with my code or am I missing some behind the scenes stuff on how the page updates?
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function makeSmaller(){
for (let i = 100; i>50; i--){
rockButtonImage.style.width = i+'%';
console.log(rockButtonImage.style.width);
sleep(50);
}
}
Upvotes: 2
Views: 43
Reputation: 2135
Modern browsers avoid unnecessary renderings of a page and wait while a JavaScript execution iteration is complete before doing a rendition.
The sleep()
function in the provided code does not really cause a browser to sleep
but rather to do a processor-intensive computation, forbidding the browser from rendering anything.
You can try using the setTimeout()
function instead, e.g.:
var i = 100;
function makeSmaller(){
console.log(rockButtonImage.style.width);
rockButtonImage.style.width = i+'%';
i--;
if (i > 50) {
setTimeout(makeSmaller, 50);
}
}
You might also find it useful to rely on CSS animations or CSS transitions instead of JavaScript for such visual effects as JS is not nearly as efficient as they are.
See also:
setTimeout
: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeoutUpvotes: 2
Reputation: 1
You have to dynamically get the DOM element getElementById and then change the width. Im not sure in which context the RockButton variable lives. Its all about the state.
Upvotes: -1