News

Make JavaScript using the functions setTimeout

It is very easy to time events in JavaScript by using the functions setTimeout() and clearTimeout(), where a section of code may be executed after a period of time has elapsed. The JavaScript function "setTimeout()" has two arguments: a string containing a JavaScript statement, which can be either a JavaScript command or a call to a function, and an integer value, which is used to set the time period in milliseconds. The function returns an integer "id."


Instructions :

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

 

"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 code in the text editor:

<body> code in the text editor:

<body onload = "colorBox()">

<div id="box">

</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.

 

 

Versi cetak

Direkomendasikan


Tentang KLATENWEB

Jasa pembuatan aplikasi web berbasis PHP dan MySQL, Web Portal, Personal, Toko Online, Sistem Informasi Akademik, SIMPeg dan Rumah Sakit, Aplikasi Facebook, dan lain sebagainya termasuk penyedia domain dan hosting unlimited murah.