Home > Web Front-end > JS Tutorial > JavaScript code to implement Sleep function_javascript skills

JavaScript code to implement Sleep function_javascript skills

WBOY
Release: 2016-05-16 19:18:27
Original
1919 people have browsed it

However, these two functions are asynchronous, and the code behind them will continue to execute during the timing process. Then write a sleep() function yourself. There are also some implementation methods circulating on the Internet, but I found the following method to be easy to understand and practical, so I share it with you here:

Copy code 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 not very accurate with the sleep() function, using this function is a good choice

The following is more complicated, friends who need it can also refer to it:

Copy the code 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");
}
}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template