Technology Programming

How to Timeout in JavaScript

    • 1). Open a new file in the text editor, and save it as "set_timeout.html." Write JavaScript <head> code in the text editor:

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml">

      <head>

      <title>Timed Color Box.</title>

      <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

    • 2). Write JavaScript <style> code in the text editor:

      <style type="text/css">

      #box

      {

      position: absolute;

      z-index: 1;

      visibility: visible;

      width: 10.0em;

      height: 5.0em;

      top: 1.0em;

      left: 1.0em;

      border : 2px solid #ccc;

      -moz-border-radius: 0.5em;

      -webkit-border-radius: 0.5em;

      text-align:center;

      padding : 1.0em;

      }

      p{

      font-size: 1.2em;

      font-weight: 900;

      color : #FFFFFF;

      }

      </style>

    • 3). Write JavaScript <script> code in the text editor:

      <script type="text/javascript">

      var color = ["red","green","orange","blue"];

      var index = 0;

      function colorBox()

      {

      document.getElementById("box").style.background = color[index];

      document.getElementById("box").innerHTML = "<p>" + color[index] + "</p>";

      if (index >= 3 )

      {

      clearTimeout();

      }

      else

      {

      setTimeout("colorBox()",1000);

      }

      index = index + 1;

      }

      </script>

      </head>

    • 4). Write JavaScript <body> code in the text editor:

      <body onload = "colorBox()">

      <div>

      </div>

      </body>

      </html>

    • 5). Save the content of the file and then open it in your Web browser. Note that the code that changes the color of the box area is run after each "timeout" period (1 second or 1000 milliseconds). After all four colors have been displayed, the "clearTimeout()" function is called to exit the process. Note that the return value "id" of the setTimeout() function has not been used. This is of value where several timeout events are called within a section of code, in order to identify each event when calling the "clearTimeout(id)" function.



Leave a reply