Home  >  Article  >  Web Front-end  >  How to implement this function if the sleep function is not provided in javascript_javascript tips

How to implement this function if the sleep function is not provided in javascript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:46:48887browse

The sleep function is not provided in javascript, but we will use this function for a long time.

One idea is to run a loop and let the program consume CPU time to achieve delay. This has a disadvantage. The CPU execution speeds of different machines are different, which can easily cause slow machines to sleep for a long time.

The author saw a clever solution from other forums, and the execution speed on different machines is consistent. Share it with everyone here.

Copy code The code is as follows:

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

}

Of course, this method still relies on idling the CPU.

Another method is to use the setTimeout() function.

The function syntax is as follows: setTimeout(code,millisec)

Usage example:

var t=setTimeout("alert('5 seconds!')",5000)

The function of this code is to execute the code after millisec. In the example, the alert function is executed after 5000 milliseconds. It can also achieve the same effect as sleep.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn