JavaScript : Timing Based Events


 

<----- Timing Based Events In JavaScript ----->


The Window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:

setTimeout(function,milliseconds)
execute a functionafter waiting a specified number of milliseconds.

setInterval(function,milliseconds)
same as setTimeOut(), but the executio of the fucnction continuously.



1. setTimeout()
2. setInterval()
3. clarTimeOut()
4. clearInterval()



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="main-div">
        <div>
            <p>Want to know my Name ?</p>
            <p id="showMyName"></p>
            <br>
            <button id="btn">Click here</button>
        </div>
    </div>

    <script>

        const myName = document.querySelector("#showMyName");
        const btn = document.querySelector("#btn");

        const showMyName = () =>{
            myName.innerHTML="Loading....."
            setTimeout(()=>{
                myName.innerHTML=("Himanshu Tiwari")
            }, 1000 )
        }

        btn.addEventListener('click'showMyName);

    </script>
</body>
</html>





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="main-div">
        <div>
            <p>Click "Try It" wait 3 sec, the page will alert "hello"</p>
            <p>clikc "STOP" to prevent the function to execute.</p>
            <p>you must click "stop" before 2 sec are up.</p>

            <button onclick="myvar = setTimeout(myFunction,2000)">Try It</button>
    
            <button onclick="clearTimeout(myvar)">stop it</button>

            <script>
                function myFunction(){
                    alert("Hello")
                }
            </script>
        </div>
    </div>
</body>
</html>