setInterval 会间隔一定时间反复执行某操作;
而setTimeout则会间隔一段时间后只执行一次;
比如:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>
setInterval 的这个效果是间隔2秒显示,然后间隔3秒隐藏,如此反复执行下去,效果就是广告图一会儿出现,一会儿隐藏,一直反复下去;
setTimeout 则是间隔2秒后显示,间隔3秒后隐藏,然后就停止了,只执行一次,效果就是显示一下广告图,然后自动关闭,之后就不会再出现了。
一般情况下,需要清除相应的定时器的话,就用相对应的clear,比如: clearInterval(); 和 clearTimeout();