How to stop the execution of a function with JavaScript?

HTMLJavascriptProgramming Scripts

To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.


You can try to run the following code to learn how to work with clearTimeout() method in JavaScript.

      <title>JavaScript clearTimeout() method</title>
            var imgObj = null;
            var animate ;
            function init(){
               imgObj = document.getElementById('myImage');
      = '0px';
            function moveRight(){
      = parseInt( + 10 + 'px';
               animate = setTimeout(moveRight,20);    // call moveRight in 20msec
            function stop(){
      = '0px';
            window.onload = init;
         <img id = "myImage" src = "/images/html.gif" />
         <p>Click the buttons below to handle animation</p>
         <input type = "button" value = "Start" onclick = "moveRight();" />
         <input type = "button" value = "Stop" onclick = "stop();" />
Published on 26-Feb-2018 15:16:35