Home  >  Article  >  Web Front-end  >  JavaScript实现Sleep函数的代码_javascript技巧

JavaScript实现Sleep函数的代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 19:18:271789browse

但是,这两个函数是异步的,在计时的过程中它们后面的代码还是会继续执行。那就自己来写个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 }
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  {  
   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");
  }
 }
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn