How to Implement sleep_javascript in js for several seconds

Source: Internet
Author: User
Js does not have its own sleep method. If you want to sleep, you need to define a method by yourself. For more information, see if js does not have its own sleep method. If you want to sleep, you need to define a method by 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 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:

The 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:

The 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:

The 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:

The 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:

The 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.