时间:2021-07-01 10:21:17 帮助过:18人阅读
但是,这两个函数是异步的,在计时的过程中它们后面的代码还是会继续执行。那就自己来写个sleep()函数吧,网上也流传了一些实现方法,不过我发现下面这个方法简单易懂而且实用,所以在这里分享给大家:
 代码如下:
console.log('start...');
console.log('now time: ' + Date(/\d{10,10}/.exec(Date.now())));
function sleep(sleepTime) {
       for(var start = Date.now(); Date.now() - start <= sleepTime; ) { } 
}
sleep(5000); // sleep 5 seconds
console.log('end...');
console.log('end time: ' + Date(/\d{10,10}/.exec(Date.now())));
如果大家的程序对sleep()函数的精确度不那么高的话,使用这个函数是个不错的选择
下面这个是复杂些的,需要的朋友也可以参考一下:
 代码如下:
function Sleep(obj,iMinSecond) 
 {  
  if (window.eventList==null)  
  window.eventList=new Array();  
  var ind=-1; 
  for (var i=0;i<window.eventList.length;i++) 
  {   
   if (window.eventList[i]==null)  
   {  
    window.eventList[i]=obj;    
    ind=i;   
    break;   
   }  
  }  
  if (ind==-1) 
  {   
   ind=window.eventList.length;   
   window.eventList[ind]=obj; 
  }  
  setTimeout("GoOn(" + ind + ")",iMinSecond); 
 } 
 function GoOn(ind) 
 {  
  var obj=window.eventList[ind]; 
  window.eventList[ind]=null; 
  if (obj.NextStep) obj.NextStep(); 
  else obj(); 
 } 
 function Test() 
 {  
  alert("sleep");  
  Sleep(this,100); 
  this.NextStep=function() 
  {  
  alert("continue"); 
  } 
 }