JavaScript实现Sleep函数的代码
2007-03-04 00:00
567 查看
但是,这两个函数是异步的,在计时的过程中它们后面的代码还是会继续执行。那就自己来写个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");
}
}
您可能感兴趣的文章:
相关文章推荐
- JavaScript实现Sleep函数的代码
- JavaScript实现Sleep函数的代码
- javascript简单拖拽实现代码(鼠标事件 mousedown mousemove mouseup)
- 用javascript实现代替marquee的滚动字幕效果代码
- javascript实现手机震动API代码
- JavaScript 报表展示实现代码
- JavaScript 报表展示实现代码
- 基于JavaScript实现图片连播和联级菜单实例代码
- JavaScript学习笔记之获取当前目录的实现代码
- 实现一个年、月、季度联动SELECT的javascript代码
- JavaScript实现对话框效果的代码实例
- 使用 Sublime Text 做 Javascript 编辑器 - 集成 SublimeCodeIntel 实现代码智能提示及自动完成
- 用JavaScript实现使用鼠标画线的示例代码
- gRaphael——JavaScript 矢量图表库:两行代码实现精美图表
- javascript 密码框防止用户粘贴和复制的实现代码
- javascript 回到顶部效果的实现代码
- JavaScript代码轻松实现网页内容禁止复制(代码简单)
- 实例代码详解javascript实现窗口抖动及qq窗口抖动
- JavaScript代码实现刷新父网页 JavaScript弹出新窗口后,关闭新窗口时,刷新父窗口
- 实例代码详解javascript实现窗口抖动及qq窗口抖动