JavaScript code for implementing the Sleep function _ javascript skills

Source: Internet
Author: User
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 ");
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.