setTimeout和setInterval的有什么不同,如何实现相互模拟?

首先我们来看一下官方解释这两个函数:

  • setTimeout:用于在指定的毫秒数后调用函数或计算表达式(官网解释)。
  • setInterval:可按照指定的周期(以毫秒计)来调用函数或计算表达式(官网解释)。

然后我根据自己的理解对setTimeout和setInterval进行重新定义,

  • setTimeout:
    • 函数:setTimeout(function(){...},millisec);
    • 含义:指的是该外部函数执行后延迟millisec(时间)后执行内部函数function,并且只执行一次,并不一定需要clearTimeout来清除;
  • clearTimeout:清除setTimeout函数,一般不需要清除,根据条件判断时候需要;
  1. 具体看一下代码:
 1 var timer = 0;      //初始化时间
 2 var testTimeout;    //定义setTimeout名称
 3 (function setTime(){
 4     testTimeout=setTimeout(function(){
 5         timer++;    //时间自增加
 6         console.log('setTimeout ===> timer: ',timer);
 7         if(timer>5){   
 8             clearTimeout(testTimeout);
 9             console.log('clearTimeout ===> timer: null');
10         }
11     },1000);
12 })();

2.执行结果:

      

3.分析:外部函数setTime只执行了一次,函数testTimeout只执行了一次,并且延迟1秒,输出1后不再执行,所有clearTimeout函数在这里根本不起作用,就需要根据具体条件进行设置;

  • setInterval:
    • 函数:setInterval(function(){...},millisec);
    • 含义:指的是在外部函数执行一次后,内部函数setInterval在固定时间millisec不断执行function,并且不会停止,除非使用clearInterval清除;
  • clearInterval:清除setInterval函数,一般需要清除,如果没有设定条件,会一直执行下去;

1.具体看代码:

 1 var timer = 0;       //初始化时间
 2 var testInterval;    //定义setInterval名称
 3 (function setInter(){
 4     testInterval=setInterval(function(){
 5         timer++;
 6         console.log('setInterval ===> timer: ',timer);
 7         if(timer>5){
 8             clearInterval(testInterval);
 9             console.log('setInterval ===> timer: null');
10         }
11     },1000);
12 })()

2.执行结果

3.分析:函数testInterval只执行了一此,内部函数testInterval在条件timer>5下一直在循环执行,直到timer=6时,函数执行clearInterval才进行了清除,不再继续执行;

前面说明了两个函数的不同,然后两个函数并非在某种特殊情况下是可以相同的,那么如何相互模拟呢?

1.setTimeout模拟setInterval

内部函数testTimeout内部执行外部函数setTime,内部函数一直在循环调用外部函数;

 1 var timer = 0;        //初始化时间
 2 var testTimeout;    //定义setTimeout名称
 3 (function setTime(){
 4     testTimeout=setTimeout(function(){
 5             timer++;
 6             console.log('setTimeout ===> timer: ',timer);
 7             setTime();
 8             if(timer>5){
 9                 clearTimeout(testTimeout);
10                 console.log('clearTimeout ===> timer: null');
11             }
12         },1000);
13     }
14 )();

运行结果

2.setInterval模拟setTimeout

内部函数testInterval执行一次就clearInterval就ok了,后面不会就继续执行

 1 var timer = 0;       //初始化时间
 2 var testInterval;    //定义setInterval名称
 3 (function setInter(){
 4     testInterval=setInterval(function(){
 5         timer++;
 6         console.log('setInterval ===> timer: ',timer);
 7         clearInterval(testInterval);
 8         if(timer>5){
 9             clearInterval(testInterval);
10             console.log('setInterval ===> timer: null');
11         }
12     },1000);
13 })();

运行结果

所以说setTimeout和setInterval各有各的优点,应用在不同场合,但是一般只需要一个setTimeout就可满足大多数情况,根据自己实际情况来判断使用哪个函数。

谢谢大家;

posted @ 2019-06-24 15:28  程序員劝退师  阅读(708)  评论(0编辑  收藏  举报