In this I want to focus on setTimeout of javascript where we can delay things.
I have created a simple HTML code which has Left Center and Right texts three times and a Button on top of them.
I used setTimeout to clear the texts in Red under the button on clicking the button.
When one clicks the button, the following should happen:
1. All the "Left" text under button will disappear in 3 seconds.
2. In the following 3 seconds "Center" text will disappear.
3. In the following 3 seconds "Right" text will disappear.
Left
Center
Right
Left
Center
Right
Left
Center
Right
I used the following code to achieve the above:
1: <html>
2: <head>
3: <style>
4: p
5: {
6: color:red;
7: font-size:20px;
8: }
9: .center
10: {
11: text-align:center;
12: }
13: .right
14: {
15: text-align:right;
16: }
17: </style>
18: <script>
19: function function1()
20: {
21: var time=3000;
22: var var0=document.getElementsByClassName("left");
23: var var1=document.getElementsByClassName("center");
24: var var2=document.getElementsByClassName("right");
25: setTimeout(function() {
26: for(var a=0;a<var0.length;a++) {
27: var0[a].style.display="none";
28: if(a===parseInt(var0.length)-1) {
29: setTimeout(function() {
30: for(var b=0;b<var1.length;b++) {
31: var1[b].style.display="none";
32: if(b===parseInt(var1.length)-1) {
33: setTimeout(function() {
34: for(var c=0;c<var2.length;c++) {
35: var2[c].style.display="none";
36: }
37: }, time);
38: }
39: }
40: }, time);
41: }
42: }
43: }, time);
44: }
45: </script>
46: </head>
47: <body>
48: <center>
49: <input type="button" onclick="function1();" value="Click here">
50: </center>
51: <p class="left">Left</p>
52: <p class="center">Center</p>
53: <p class="right">Right</p>
54: <p class="left">Left</p>
55: <p class="center">Center</p>
56: <p class="right">Right</p>
57: <p class="left">Left</p>
58: <p class="center">Center</p>
59: <p class="right">Right</p>
60: </body>
61: </html>
In the above code, I used a setTimeout method and provided a delay of 3000 ms (3 seconds), In the method, I have formatted display to none in javascript and when the last tag of class name "left" is reached, I did the same for Center in the main setTimeout and created a setTimeout method for center inside and in Center's setTimeout method, I created another setTimeout for "right".
One can do really cool stuff with this method.
Suggestions are really appreciated.
One can do really cool stuff with this method.
Suggestions are really appreciated.
No comments:
Post a Comment