var height = 20; var width = 20; var id = null; function animation() { height++; width++; var element = document.getElementById("box"); element.style.height = height + "px"; element.style.width = width + "px"; console.log(element.style.height); //inside the first frame, queue the execution of next frame. //only one callback is queued at a time. therefore queue is not exhausted. id = requestAnimationFrame(animation); } function start_animation() { //start the first frame id = requestAnimationFrame(animation); } function cancel_animation() { //cancel the latest frame. cancelAnimationFrame(id); }
<button onclick="start_animation()">Start Animation</button> <button onclick="cancel_animation()">Cancel Animation</button> <div id="box" style="height: 20px; width: 20px; background-color: red"></div>