码迷,mamicode.com
首页 > Web开发 > 详细

setInterval 和 setTimeout 的区别 JS学习笔记2015-6-26(第67天)

时间:2015-06-26 23:45:30      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

setInterval 会间隔一定时间反复执行某操作;

而setTimeout则会间隔一段时间后只执行一次;

 

比如:

技术分享
 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <style>
 7 body { background:url(img/sina.jpg) no-repeat center 0; text-align:center; }
 8 img { display:none; }
 9 </style>
10 <script>
11 window.onload = function (){
12     var miaov = document.getElementById(miaov);
13     
14     setInterval( function(){
15         miaov.style.display = inline-block;
16         
17         setInterval(function(){
18             miaov.style.display = none;
19         }, 3000);
20         
21     },  2000);
22 };
23 </script>
24 </head>
25 
26 <body>
27 
28 <img id="miaov" src="img/miaov.jpg" />
29 
30 </body>
31 </html>
View Code

 

技术分享
 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <style>
 7 body { background:url(img/sina.jpg) no-repeat center 0; text-align:center; }
 8 img { display:none; }
 9 </style>
10 <script>
11 window.onload = function (){
12     var miaov = document.getElementById(miaov);
13     
14     setTimeout( function(){
15         miaov.style.display = inline-block;
16         
17         setTimeout(function(){
18             miaov.style.display = none;
19         }, 3000);
20         
21     },  2000);
22 };
23 </script>
24 </head>
25 
26 <body>
27 
28 <img id="miaov" src="img/miaov.jpg" />
29 
30 </body>
31 </html>
View Code

setInterval 的这个效果是间隔2秒显示,然后间隔3秒隐藏,如此反复执行下去,效果就是广告图一会儿出现,一会儿隐藏,一直反复下去;

 

setTimeout 则是间隔2秒后显示,间隔3秒后隐藏,然后就停止了,只执行一次,效果就是显示一下广告图,然后自动关闭,之后就不会再出现了。

 

一般情况下,需要清除相应的定时器的话,就用相对应的clear,比如: clearInterval(); 和 clearTimeout(); 

setInterval 和 setTimeout 的区别 JS学习笔记2015-6-26(第67天)

标签:

原文地址:http://www.cnblogs.com/zhangxg/p/4603397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!