This shows how to run animation, change speed of moving block and stop and restart it. This is a modiļ¬ed version of initial code I saw at w3schools web site with lots of changes I made to it.
Clicking on HTML runs the code. The source code is
<!DOCTYPE html> <!-- By Nasser M. Abbasi. Nov 12, 2023--> <html> <style> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; } </style> <body> <div style=" margin: 8px; display: block;"> <button onclick="restart()">restart</button> <button onclick="stop()">stop</button> <button onclick="do_continue()">continue</button> <button onclick="faster()">faster</button> <button onclick="slower()">slower</button> </div> <div id="container"> <div id="animate"></div> </div> <p id="the_frame_rate"></p> <p id="position"></p> <script> let g_id = null; let g_delay = 5; let g_pos = 0; document.getElementById("position").innerText = "current position : (" + 0 + " , " + 0 + ")"; function stop() { if( g_id != null) { clearInterval(g_id); g_id = null; } } function do_continue() { if( g_id != null) { clearInterval(g_id); g_id = null; } move_it(); } function slower() { g_delay = g_delay + 1; var myP = document.getElementById("the_frame_rate"); myP.innerText = "current frame rate : " + g_delay; if( g_id != null) { clearInterval(g_id); g_id = null; } move_it(); } function faster() { if( g_delay>0 ) { g_delay = g_delay - 1; var myP = document.getElementById("the_frame_rate"); myP.innerText = "current frame rate : " + g_delay; } if( g_id != null) { clearInterval(g_id); g_id = null; } move_it(); } function restart() { if( g_id != null) { clearInterval(g_id); g_id = null; } g_pos = 0; move_it(); } function move_it() { const elem = document.getElementById("animate"); g_id = setInterval(frame, g_delay); function frame() { var myP1 = document.getElementById("position"); var myP2 = document.getElementById("the_frame_rate"); if (g_pos == 350) { //clearInterval(id); g_pos = 0; //g_id = null; } else { g_pos++; elem.style.top = g_pos + "px"; elem.style.left = g_pos + "px"; } myP1.innerText = "current position : (" + elem.style.top + " , " + elem.style.left + ")"; myP2.innerText = "current frame rate : " + g_delay; } } </script> </body> </html>