LearnFast.Ninja

setTimeout Javascript example

In this example we trigger the function with onload in the body. In doLoop function we do recursion using the set time out. we create instance of setTimeout with the doLoop and two seconds delay. We also want it to work 4 times so after that we clear the timeout.

Working example code:

<!DOCTYPE html>

<html>

<head>

    <title>Untitled Page</title>

    <script type="text/javascript">

        var LoopCounter = 0;

 

        function doLoop() {

            if (LoopCounter < 4) {

                LoopCounter++;

                alert(LoopCounter);

                MyTimout = setTimeout(doLoop, 2000);

                //MyTimout = setTimeout("doLoop()", 2000);

            }

            else {

                clearTimeout(MyTimout);

            }

        }

    </script>

</head>

<body onload="doLoop()">

</body>

</html>


Result:


Tags

javascript

settimeout cleartimeout delay