一、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>
运行效果: