In this JavaScript Tutorial, we will learn how to perform delayed function calls. Here, we will use setInterval and setTimeout JavaScript functions to call a method after some second elapses. This video also helps you understand what is the difference between setInterval and setTimeout.
Code Snippets
For Demo 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>Learn Java Script</TITLE> <script type="text/javascript" > function Print() { //Let us say the base time is T setTimeout("DelayedPrint('Timeout Called')", 3000); //Called in 3 Secs from T setTimeout("DelayedPrint('Timeout Called')", 4000); //Called in 4 Sec from T setTimeout("DelayedPrint('Timeout Called')", 5000); //Called in 5 Sec from T setTimeout("DelayedPrint('Timeout Called')", 6000); //Called in 6 Sec from T setTimeout("DelayedPrint('Timeout Called')", 7000); //Called in 7 Sec from T setTimeout("DelayedPrint('Timeout Called')", 10000); //Called in 10 Secs from T } function DelayedPrint(msg) { document.getElementById("h3Out").innerHTML += (msg + "<br/>"); } </script> </HEAD> <BODY> <H1> JavaScript Functions Example </H1> <br/> <input type="button" value="Call Timer Delay" onclick="Print()" /> <h3 id="h3Out"></h3> </BODY> </HTML> |
For Demo 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>Learn Java Script</TITLE> <script type="text/javascript" > var Timer; function TimerStart() { Timer = setInterval("DelayedPrint('Timeout Called')", 1000); } function DelayedPrint(msg) { document.getElementById("h3Out").innerHTML += (msg + "<br/>"); } function TimerStop() { clearInterval(Timer); } </script> </HEAD> <BODY> <H1> JavaScript Example - Mouse-Down and Mouse-Up Handlers </H1> <br/> <input type="button" value="Hold Print" onmousedown="TimerStart()" onmouseup="TimerStop()" /> <br/> <h3 id="h3Out"></h3> </BODY> </HTML> |
Categories: JavaScript-Tube