本文介绍了在JavaScript中实现类似Sleep暂停功能的两种代码方案。由于原生JS不支持sleep,文章通过setTimeout结合事件列表数组的方式,演示了如何暂停函数执行并在指定时间后继续。包含详细代码及原理说明,适用于需要模拟同步暂停逻辑的场景。
第一种Sleep实现方案
示例代码如下:
<SCRIPT LANGUAGE="JavaScript">
<!--
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,10000);
this.NextStep=function()
{
alert("continue");
}
}
Test();
//-->
</SCRIPT>第二种Pause实现方案
以下是其他开发者提供的另一种实现方案:
示例代码如下:
<script language="javascript">
/*Javascript中暂停功能的实现
由于原生Javascript不支持sleep,且vbscript无法使用doEvents,因此需编写自定义函数来实现暂停逻辑。
在Javascript这种弱类型语言中,函数可作为对象进行调用。
例如:
function Test(){
alert("hellow");
this.NextStep=function(){
alert("NextStep");
}
}
可通过如下方式调用:var myTest=new Test();myTest.NextStep();
实现暂停时,可将函数拆分为两部分:暂停前逻辑保持不变,暂停后执行的代码置于this.NextStep中。
为实现暂停与恢复的控制,需编写两个独立函数分别处理暂停和继续逻辑。
暂停函数定义如下:
*/
function Pause(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 + ")",1000);
}
/*
该函数将目标函数存入window.eventList数组,并通过setTimeout触发继续函数。
继续函数定义如下:
*/
function GoOn(ind){
var obj=window.eventList[ind];
window.eventList[ind]=null;
if (obj.NextStep) obj.NextStep();
else obj();
}
/*
该函数执行被暂停函数的NextStep方法;若不存在该方法,则重新调用原函数。
函数定义完成后,可作如下测试:
*/
function Test(){
alert("hellow");
Pause(this,1000);//调用暂停函数
this.NextStep=function(){
alert("NextStep");
}
}
</script>