JavaScript does not provide sleep function how to implement this function _javascript tips

Source: Internet
Author: User
Tags sleep function
The sleep function is not available in JavaScript, and we use this feature for the length of time.

One idea is to run a cycle of the body, so that the program consumed CPU time to achieve delay. This has a problem, the different machine CPU execution speed is not the same, this can easily cause slow machine will sleep for a long time.

I see a witty solution from other forums, and the speed of execution is the same on different machines. Share with you here.
Copy Code code as follows:

function sleep (n)
{
var start=new Date (). GetTime ();
while (true) if (new Date (). GetTime ()-start>n) the break;

}

Of course, this method is still rely on idling CPU method.

Another method is to use the settimeout () function.

The function syntax is as follows: SetTimeout (CODE,MILLISEC)

Use Example:

var t=settimeout ("Alert (' 5 seconds! ')", 5000)

The function of this code is to execute code after millisec, in which the alert function is executed after 5000 milliseconds. You can also achieve the same effect as sleep.
Related Article

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.