The sleep function is not provided in JavaScript, and we will use this function for a long time.
There is an idea to run a loop body to make the program consume CPU time to achieve delay. This has a disadvantage. The execution speed of different machines is different, which can easily lead to slow machines that will SLEEP for a long time.
The author saw a smart solution from other forums, and the execution speed on different machines is consistent. Share it with you here.
The code copy 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 idle CPU.
Another way is to use the setTimeout() function.
The function syntax is as follows: setTimeout(code,millisec)
Example of usage:
var t=setTimeout("alert('5 seconds!')",5000)
The function of this code is to execute the code code after millisec. In the example, the alert function is executed after 5000 milliseconds. It can also achieve the same effect as sleep.