Function proto-type
Code Block |
---|
|
setTimeout(function, milliseconds, param1, param2, ...) |
Below code shows "Hello" after 3 seconds
Code Block |
---|
|
setTimeout(function(){ alert("Hello"); }, 3000); |
Below code shows increased number in innerHTML every 3 seconds
Code Block |
---|
language | xml |
---|
title | timer1.htm |
---|
|
<html>
<script>
var myCnt=0;
function alertFunc() {
myCnt++;
document.getElementById( "main").innerHTML = myCnt;
setTimeout(alertFunc, 3000); // repeat the same event
}
setTimeout(alertFunc, 3000);
</script>
<body>
<div id="main">The number will be increased and displayed here every 3 seconds</div>
</body>
</html> |
Below code draws 10x10 table on HTML body when page is loading, and change its background color of table block with its innerHTML:
Code Block |
---|
language | xml |
---|
title | timer2.htm |
---|
|
<html>
<script type="text/javascript">
var myCnt=0;
var myColor=[ "#ef3fef","#ef6fef","#fefe2e","#fefe4e","#ef9f9f","#ef9f3f","#fe3f3f","#7e3f3f","lightgreen","lightgray","pink","cyan","yellow"];
var clrCnt=myColor.length;
var blockCnt=0;
function drawBody() {
var sBody="<table border=1>";
for(i=0; i<10; i++) {
sBody += "<tr>";
for( j=0; j<10; j++) {
sBody += "<td width=70 height=70 id='block" + blockCnt.toString() + "' align=center>0</td>";
blockCnt++;
}
sBody += "</tr>";
}
sBody += "</table>";
document.body.innerHTML = sBody;
}
function alertFunc() {
myCnt++;
tmpColor = Math.floor(Math.random()*clrCnt);
tmpBlock = Math.floor(Math.random()*blockCnt);
document.getElementById( "block" + tmpBlock).style.backgroundColor = myColor[tmpColor];
document.getElementById( "block" + tmpBlock).innerHTML = "<font color=-2>" + myCnt + "</font>";
setTimeout(alertFunc, 100); // repeat the same event
}
</script>
<!-- Update HTML body when page is loading" -->
<body onLoad="javascript:drawBody();">
</body>
<script type="text/javascript">
// Launch Timer
setTimeout(alertFunc, 2000);
</script>
</html> |