What are use of “clearTimeout” and “clearInterval” in JS?

0 votes
35 views
Ravi Vishwakarma asked 8 days ago in Web Application by Ravi Vishwakarma

What are use of “clearTimeout” and “clearInterval” in JS?

1 Answer

0 votes
Ethan Karla answered 5 days ago by Ethan Karla
The clearTimeout() method clears a timer set with the setTimeout() method. The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.
myVar = setTimeout('javascript function', milliseconds);
Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.
Example 
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
    <button onclick='myFunction()'>Try it</button>
    <button onclick='myStopFunction()'>Stop the alert</button>
    <p>this is show alert box in 3 second, if you want stop then click 'stop alert button'</p>
    <script>
        var myVar;
        function myFunction() {
            myVar = setTimeout(function () {
                alert('this alert show within 3 second ');
            }, 3000);
        }
        function myStopFunction() {
            clearTimeout(myVar);
        }
    </script>
</body>
</html>
The clearInterval() method clears a timer set with the setInterval() method. The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
To be able to use the clearInterval() method, you must use a variable when creating the interval method.
myVar = setInterval('javascript function', milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
clearInterval(myVar);
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<p>In this example, the setInterval() method executes the setColor() function once every 300 milliseconds, which will toggle between two background colors.</p>
<button onclick='stopColor()'>Stop Toggling</button>
<button onclick='startColor()'>start Toggling</button>
<script>
    var myVar = setInterval(setColor, 10);
    function setColor() {
        var x = document.body;
        x.style.backgroundColor = x.style.backgroundColor == 'red' ? 'yellow' : 'red';
    }
    function stopColor() {
        clearInterval(myVar);
    }
    function startColor()
    {
        myVar = setInterval(setColor, 10);
    }
</script>
</body>
</html>