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


    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(); 

  • 相关阅读:
    星辉信息odoo教程
    星辉odoo教程
    Python 语言简介与入门
    DVWA漏洞演练平台
    植物大战僵尸:分析植物的攻击速度
    植物大战僵尸:寻找召唤僵尸关键CALL
    植物大战僵尸:查找植物叠加种植CALL
    植物大战僵尸:植物栏无冷却的找法
    植物大战僵尸:寻找向日葵的生产速度
    dpwwn: 1 Vulnhub Walkthrough
  • 原文地址:https://www.cnblogs.com/zhangxg/p/4603397.html
Copyright © 2020-2023  润新知