As you know, JavaScript does not have built-in sleep () functions that we commonly use. Only the timer setTimeout () and the cyclic timer setInterval (). However, these two functions are asynchronous, the code behind them will continue to be executed during timing. Let's write a sleep () function by myself. Some implementation methods are also circulating on the Internet. However, I found this method is easy to understand and practical, so I will share it with you here:
The Code is as follows:
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 ())));
If your program is less accurate to the sleep () function, using this function is a good choice.
The following is a bit more complex. For more information, see:
The Code is as follows:
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 ");
}
}