There is no sleep method in js. If you want to hibernate, you must define a method yourself.
function sleep(numberMillis) { var now = new Date(); var exitTime = now.getTime() + numberMillis; while (true) { now = new Date(); if (now.getTime() > exitTime) return; } }The following are the additions:
In addition to Narrative JS, jwacs(Javascript With Advanced Continuation Support) is also committed to avoid writing callback functions that are troublesome asynchronously called by extending JavaScript syntax. The sleep implemented with jwacs, the code is as follows:
The code copy is as follows:
function sleep(msec) {
var k = function_continuation;
setTimeout(function() { resume k <- mesc; }, msec);
suspend;
}
This syntax is even more scary, and it is a thread method name that is not recommended in Java. Frankly I tend toward Narrative JS.
Like Narrative JS, jwacs also needs to be precompiled, and the precompiler is written in LISP language. It is also the Alpha version at the moment. For more introductions and comparisons of the two, please refer to the new article on SitePoint: Eliminating async Javascript callbacks by preprocessing
When writing complex JavaScript scripts, there is sometimes a need to hope that the script can stall for a specified period of time, similar to the effect achieved by the Thread.sleep in java or the sleep command in sh script.
As we all know, JavaScript does not provide thread control functions similar to Java. Although there are two methods, setTimeout and setInterval, which can perform some timed execution control, they cannot meet all requirements. There have always been many people asking how to implement sleep/pause/wait in JavaScript, and there are indeed some very lame solutions:
The easiest and worst way is to write a loop, the code may be as follows:
The code copy is as follows:
function sleep(numberMillis) {
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
The above code actually does not sleep the script interpreter, and it also has the effect of quickly increasing the CPU to high load. The browser will even be in a fake death state for that period of time.
Secondly, smart people use IE's special dialog box implementation to connect with each other. The code may be as follows:
The code copy is as follows:
function sleep(timeout) {
window.showModalDialog("javascript:document.writeln('<script>window.setTimeout(function () { window.close(); }, " + timeout + ");<//script>');");
}window.alert("before sleep...");
sleep(2000);
window.alert("after sleep...");
Needless to say, only IE supports (IE7 cannot achieve its goal due to security restrictions).
In addition, there are also tricks such as using Applet or calling Windows Script Host's WScript.Sleep(), which are all last resorts.
Finally, there are smarter people who have developed perhaps the best solution. Let’s look at the code first:
The code copy is as follows:
function sleep(millis) {
var notifier = NjsRuntime.createNotifier();
setTimeout(notifier, millis);
notifier.wait->();
}
That's right, seeing the syntax of ->() is astonishing as seeing the Prototype's $() function. However, this script will report syntax errors directly in the browser. In fact, they need to be precompiled into JavaScript approved by the client browser. The compiled script is as follows:
The code copy is as follows:
function sleep(millis){
var njf1 = njen(this,arguments,"millis");
nj:while(1) {
try{switch(njf1.cp) {
case 0:njf1._notifier=NjsRuntime.createNotifier();
setTimeout(njf1._notifier,njf1._millis);
njf1.cp = 1;
njf1._notifier.wait(njf1);
return;
case 1:break nj;
}} catch(ex) {
if(!njf1.except(ex,1))
return;
}}
njf1.pf();
}
I can't understand it, and I don't want to understand it anymore. All of these tasks will be implemented by Narrative JavaScript - a JS extension that provides asynchronous blocking functionality for us. We only need to write the weird ->() syntax before, and then implement the sleep effect through pre-static compilation or dynamic compilation of the foreground.
Narrative JavaScript claims to free you from dizzy callback functions and write clear Long Running Tasks. Currently, it is still the version of alpha, and there is an example of a moving button on the Example page. Source code download is also available on the homepage. With my weak basic knowledge, I can only barely see that the implementation of the state machine is simulated in the code. I hope that friends who are proficient in algorithms can parse it for us.
Finally, I've always had my point of view: Please keep JavaScript simple unless it's necessary. Before JavaScript can provide native threading support, perhaps we can change the design to avoid asynchronous blocking applications.
A tortuous implementation of bugs
<script type"text/javascript">/*Implementation of pause function in Javascript Javascript itself does not have pause function (sleep cannot be used) At the same time, vbscript cannot use doEvents, so write this function to implement this function. JavaScript is a weak object language, and a function can also be used as an object. For example: [code]function Test(){ alert("hellow"); this.NextStep=function(){ alert("NextStep"); }} We can call var myTest=new Test(); myTest.NextStep(); When we do pause, a function can be divided into two parts, the unchanged before the pause operation, and put the code to be executed after the pause in this.NextStep. In order to control pause and continuation, we need to write two functions to implement pause and continuation functions respectively. The pause function is as follows: */function Pause(obj,iMinSecond){ if (window.eventList==null) window.eventList=new Array(); var ind=-1; for (var i=0;i<window.eventList.length;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 + ")",1000);}/*This function puts the function to be paused into the array window.eventList, and at the same time calls the continuing function through setTimeout. The continuing function is as follows: */function GoOn(ind){ var obj=window.eventList[ind]; window.eventList[ind]=null; if (obj.NextStep) obj.NextStep(); else obj();}/*This function calls the NextStep method of the suspended function. If this method is not available, the function will be called again. After the function is written, we can write the following volume: */function Test(){ alert("hellow"); Pause(this,1000);//Calling the pause function this.NextStep=function(){ alert("NextStep"); }}</script>