Js custom method implementation stay for several seconds sleep, jssleep
Js does not have its own sleep method. To sleep, define a method.
function sleep(numberMillis) { var now = new Date(); var exitTime = now.getTime() + numberMillis; while (true) { now = new Date(); if (now.getTime() > exitTime) return; } }
The following is a supplement:
In addition to Narrative JS, javasacs (Javascript With Advanced Continuation Support) is also committed to avoiding the headache of writing callback functions that call asynchronously by extending JavaScript syntax. Run the following code to implement sleep with javasacs:
Copy codeThe Code is as follows:
Function sleep (msec ){
Var k = function_continuation;
SetTimeout (function () {resume k <-mesc ;}, msec );
Suspend;
}
This syntax is even more frightening, and it is also the name of the thread method not recommended in java. Frankly speaking, I prefer Narrative JS.
Like Narrative JS, javasacs also needs to be pre-compiled, and the pre-compiler is written in LISP. It is also the Alpha version. For more information and comparisons, see the new article on SitePoint: Eliminating async Javascript callbacks by preprocessing.
When writing complex JavaScript scripts, sometimes there is a need for the script to be stuck for a specified period of time, similar to the effect of the Thread. sleep in java or the sleep command in sh script.
As we all know, JavaScript does not provide a function similar to Java thread control. Although there are setTimeout and setInterval methods that can be used for some scheduled execution control, they cannot meet all requirements. For a long time, many people have been asking how to implement sleep, pause, and wait in JavaScript, and there are some really bad solutions:
The simplest and worst way is to write a loop. The code may be as follows:
Copy codeThe Code 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;
}
}
In fact, the above Code does not let the script interpreter sleep down, and has the function of quickly enabling the CPU to reach high load. The browser may even be in the suspended state during this period of time.
Second, smart people use the special IE dialog box to perform smooth operations. The code may be as follows:
Copy codeThe Code 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 ...");
The disadvantage is not to mention that only Internet Explorer supports Internet Explorer (IE7 cannot achieve its goal due to security restrictions ).
In addition to the above, there are also WScript. Sleep () and other ideas that use the Applet or call the Windows Script Host. These are all measures of the last resort.
Finally, a smarter person developed the best solution. Let's look at the code first:
Copy codeThe Code is as follows:
Function sleep (millis ){
Var notifier = NjsRuntime. createNotifier ();
SetTimeout (notifier, millis );
Notifier. wait-> ();
}
That's right. Seeing the syntax like> () is like seeing the $ () function of Prototype, it surprised me. However, the script directly in the browser reports syntax errors. In fact, they need to be compiled into JavaScript approved by the client browser. The compiled script is as follows:
Copy codeThe Code 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.0000t (ex, 1 ))
Return;
}}
Njf1.pf ();
}
I don't want to understand it. All this work will be done by Narrative JavaScript-a JS extension that provides the asynchronous blocking function. We only need to write the previous weird-> () syntax, and then execute the sleep through the background pre-static compilation or the foreground dynamic compilation.
Narrative JavaScript claims that it can free you from dizzy callback functions and Write clear Long Running Tasks. The current version is alpha. There is an Example of moving buttons on the Example Page. Source code download is also provided on the home page. With my weak basic knowledge, I can barely see that the implementation of the state machine is simulated in the code. I hope that a friend who is proficient in algorithms can resolve the problem for us.
Finally, I keep my point of view: Keep JavaScript simple unless necessary. Before JavaScript can provide native thread support, we may be able to change the design to avoid asynchronous blocking of applications.
Twists and turns with bugs
<Script type "text/javascript">/* Implementation of the pause function in Javascript javascript itself does not have the pause function (sleep cannot be used) and vbscript cannot use doEvents, therefore, 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 pause, we can divide a function into two parts, which are unchanged before the pause operation and put the code to be executed after the pause in this. nextStep. To control the pause and continue, we need to write two functions to implement the pause and continue 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);}/* put the function to be paused in the Array window. in eventList, setTimeout is used to call the continuation function. The continue function is as follows: */function GoOn (ind) {var obj = window. eventList [ind]; window. eventList [ind] = null; if (obj. nextStep) obj. nextStep (); else obj ();}/* call the NextStep method of the suspended function. If this method is not available, call the function again. After the function is compiled, we can perform the following operations: */function Test () {alert ("hellow"); Pause (this, 1000); // call the Pause function this. nextStep = function () {alert ("NextStep") ;}}</script>
In js, how does one make an object stay for several seconds to execute the onmouseover event?
If the amount is blocked, it will not work. You can use the setTimeout method.
SetTimeout ("alert ('Sorry, you have to wait for a long time')", 3000)
For example, onmouseover triggers a method, and then execute setTimeout in the method to point to the method you want to execute, set the delay time, and you can
How does the js sleep function not respond?
There is no sleep command in JavaScript. Generally, you can use the existing setTimeout (), clearTimeout (), and setInterval (). In this case, you should use built-in functions. But if you really need an option of sleep or wait statement, you can see what code can work best. What are the requirements for the sleep method? Let's take a look at the following authoritative description to illustrate the problem: Pause the current thread of the application, the time is the specified number of milliseconds, allowing other processes (or threads) to continue running. The following are various methods for implementing the sleep function in javascript: (1) JavaScript sleep through loops (2) JavaScript sleep through Java Applet (3) JavaScript sleep through Flash (4) javaScript sleep is implemented through XMLHttp through the following code: <script type = "text/JavaScript"> // bad implementationfunction sleep (milliSeconds) {var startTime = new Date (). getTime (); // get the current time while (new Date (). getTime () <startTime + milliSeconds); // hog cpu} </script> Use a while loop to continuously check the current time in the first row. When the time is reached, we will stop the loop. This loop runs fast, and the browser will occupy all valuable CPU resources. The check time may not seem too long, but thousands (or tens of thousands) of times per second may affect the performance of your computer. Using Java Applet to implement JavaScript sleep this solution is to insert a Java Applet and communicate with java applets through Javascript. Java Applets uses Java Thread. sleep () method sleep thread (does not occupy resources ). <Applet code = "DevCheater. class "name =" devCheater "id =" devCheater "mayscript =" true "height =" 1 "width =" 1 "> </applet> <script type =" text/javascript "> function sleep (milliSeconds) {// runs Java Applets sleep method document. devCheater. sleep (milliSeconds) ;}</script> this method does not freeze other javascript on all pages (except when Chrome is used ). Unfortunately, it needs to install a Java Plug-in. If we try Java by implementing JavaScript sleep through Flash, why not try adobe flash. I created a Flash application named flashSleep (). I use javascript to call my... the remaining full text>