一、setTimeout
setTimeout("函數",時間)
setInterval(fn,5000);//每隔5秒執行一次fn
setTimeout(fn,5000);//5秒之後執行一次fn
二、跳轉頁面
window.location.href="http://www.baidu.com";
函數自己調用自己成為“遞歸調用”
案例:
1、發送短信驗證倒計時
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 <style>
7 .box{
8 margin: 100px auto;
9 text-align: center;
10 }
11 #btn{
12
13 }
14 </style>
15 <script>
16 window.onload=function(){
17 var btn=document.getElementById("btn");
18 var count=60;
19 var timer=null;//定時器名稱
20 btn.onclick=function(){
21 clearInterval(timer);
22 this.disabled="true";//this指向btn
23 var that=this;//使用that存儲目前this
24 timer=setInterval(sendTextMessage,1000);//開啟定時器
25 function sendTextMessage(){
26 count--;
27 if(count>=0){
28 that.innerHTML="還剩餘"+count+"秒";
29 }else{
30 that.innerHTML="重新發送短信";
31 that.disabled=false;
32 clearInterval(timer);
33 count=60;
34 }
35
36 }
37 }
38 }
39 </script>
40 </head>
41 <body>
42 <div class="box">
43 <input type="text">
44 <button id="btn">點選發送短信</button>
45 </div>
46 </body>
47 </html>
運作效果:
2、5秒後跳轉頁面
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>跳轉頁面</title>
6 <style>
7 #demo{
8 margin: 100px auto;
9 color: #000;
10 font-size: 30px;
11 text-align: center;
12 }
13 #demo a{
14 text-decoration: none;
15 color: red;
16 }
17 </style>
18 </head>
19 <body>
20 <div id="demo"></div>
21 </body>
22 <script>
23 var demo=document.getElementById("demo");
24 var count=5;
25 var speed=1000;
26 setTimeout(goIndexPage,speed);//1秒之後 執行goIndexPage函數
27 function goIndexPage(){
28 count--;
29 demo.innerHTML="<a href='http://www.baidu.com'>本頁面将在"+count+"秒之後跳轉頁面</a>";
30 if(count<1){
31 window.location.href="http://www.baidu.com";//跳轉頁面
32
33 }else{
34 setTimeout(goIndexPage,speed);//遞歸調用 setTimeout隻執行一次
35 }
36 }
37 </script>
38 </html>
運作效果:
3、5秒後關閉廣告
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>5s之後關閉廣告</title>
6 <style>
7 *{
8 margin: 0;
9 padding: 0;
10 }
11 #left{
12 float: left;
13 }
14 .box{
15 float: left;
16 margin: 100px;
17 }
18 #right{
19 float: left;
20 }
21 </style>
22 </head>
23 <body>
24 <div id="left"><img src="1.gif" alt=""></div>
25 <div class="box">
26 <p>山上有座廟,廟裡有個和尚</p>
27 <p>山上有座廟,廟裡有個和尚</p>
28 <p>山上有座廟,廟裡有個和尚</p>
29 <p>山上有座廟,廟裡有個和尚</p>
30 <p>山上有座廟,廟裡有個和尚</p>
31 </div>
32
33 <div id="right"><img src="2.gif" alt=""></div>
34
35 </body>
36 <script>
37 function $(id){return document.getElementById(id);}
38 function hide(id){
39 $(id).style.display="none";
40 }
41 function show(id){
42 $(id).style.display="block";
43 }
44 setTimeout(closeAd,5000);
45 function closeAd(){
46 hide("right");
47 hide("left");
48 }
49 </script>
50 </html>
運作效果: