The sleep in JS, sequential execution __javascript

Source: Internet
Author: User
Tags define function error handling exception handling sleep function terminates
recently upgraded blog, need to implement a pause in JS, or a small number of disturbing people, the total does not reach the expected effect, or the function is divided into several parts, or the event mechanism, in fact, single-threaded is not a multiple-thread sleep function, so can only this process check. In addition to narrative JS, Jwacs (JavaScript with Advanced continuation Support) is also dedicated to extending JavaScript syntax to avoid writing callback functions that make a headache asynchronous call. The sleep that is implemented with Jwacs, the code is this:

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 a thread method that is not recommended for use in Java. Frankly, I tend to narrative JS.

Like narrative js, Jwacs also needs to be precompiled, the precompiled compiler is written in LISP language. is currently Alpha version. More introduction and comparison of both can be found in the new article on SitePoint: eliminating async Javascript callbacks by preprocessing

When writing complex JavaScript scripts, there are times when you want the script to stall for a specified period of time, similar to the effect achieved by the sleep command in Thread.Sleep or SH scripts in Java.

As we all know, JavaScript does not provide a Java-like thread control function, although there are settimeout and setinterval two methods can do some timing control, but does not meet all requirements. A lot of people have been asking how to implement sleep/pause/wait in JavaScript, and there are some really crappy solutions:

The simplest and worst way to do this is to write a loop with the following code:

function Sleep (numbermillis) {
    var now = new Date ();
    var exittime = now.gettime () + Numbermillis;
    while (true) {now
        = new Date ();
        if (Now.gettime () > Exittime) return
            ;
    }

The code above does not allow the script interpreter to sleep, and it has the added effect of getting the CPU up and down to high load quickly. The browser may even be in suspended animation for that period of time.

The second is the clever use of IE Special dialog box to achieve the winding, the code may be 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 say, only IE support (IE7 because of security restrictions also can not achieve the purpose).

In addition to the above, there is the use of applets or invoke Windows Script host Wscript.Sleep () and so on tricks, these are the last resort expedient.

Finally have a smarter person, developed perhaps the best solution, first look at the code:

function Sleep (Millis) {
    var notifier = Njsruntime.createnotifier ();
    SetTimeout (notifier, Millis);
    Notifier.wait-> ();
}

Yes, I was surprised to see the syntax of -> () like the $ () function I just saw prototype. However, this script will report syntax errors directly in the browser. In fact, they require JavaScript that is precompiled into the client browser's approval. The compiled script 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 do not understand, do not want to see understand. All of this work will be done by narrative JavaScript ———— a JS extension that provides asynchronous blocking functionality. We just need to write that weird-> () syntax, and then we can achieve the sleep effect through the background pre-static compilation or the foreground dynamic compilation.

Narrative JavaScript claims to free you from the dizzy callback function, writing a clear long Running Tasks. Currently an alpha version, there is an example of a moving button on the Example page. The home page also provides the source download. With my weak basic knowledge, I can only barely see the code to simulate the implementation of the state machine, I hope to have proficient in the algorithm of friends to resolve for us.

Finally, I have always been the point of view: unless it is necessary, please keep javascript simple. Before JavaScript can provide native thread support, perhaps we can change the design to avoid the application of asynchronous blocking.

Reference article: Agile ajax-narrative javascript-cleaner Code for Long Running Tasks faqts-how doing I pause execution in JAVASCRI  Pt? ========== the twists and turns of a bug

<script language= "JavaScript" >
Implementation of pause function in/*javascript
JavaScript does not have a pause function (sleep cannot be used) while VBScript cannot use DoEvents, so writing this function implements this function.
JavaScript as a weak object language, a function can also be used as an object.
Like what:
function Test () {
Alert ("Hellow");
This. Nextstep=function () {
Alert ("NextStep");
}
}
We can call Var mytest=new Test (); Mytest.nextstep ();

We can do it when we're done. A function is divided into two parts, the same before the pause operation, put the code to be executed after the pause in this. In NeXTSTEP.
To control pause and continue, we need to write two functions to implement the pause and continue function separately.
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);
}
/*
The function places the function to be paused in the array window.eventlist, while the continuation function is called through the settimeout.

The continuation function is as follows:
*/

Function GoOn (Ind) {
 var obj=window.eventlist[ind];
 window.eventlist[ind]=null;
 if ( Obj. NextStep) obj. NextStep ();
 else obj ();
}
/*
The function calls the NeXTSTEP method of the function being paused, and calls the function again if there is no such method.


After the function is written, we can make the following book:
*/
function Test () {
Alert ("Hellow");
Pause (this,1000),/call suspend function
This. Nextstep=function () {
Alert ("NextStep");
}
}
</script>


Implementation of JavaScript sequential execution:
http://www.cnlei.org/blog/article.asp?id=297
JavaScript Series-Synchronous or asynchronous:
Http://blog.iecn.net/blog/html/do-showone-tid-966.html
Implementation of pause functionality in javascript:
Http://blog.csdn.net/snakegod/archive/2004/09/22/112810.aspx
JavaScript Sleep function:
Http://blog.csdn.net/gaooo/archive/2007/02/25/1514096.aspx
The article is reproduced from the home of the script: http://www.jb51.net/html/200703/23/7505.htm
Scrolling bulletin board that can be paused
http://www.codebit.cn/pub/html/javascript/tip/pausing_up_down_scroller/

Two, a function calls B function, B can not only control itself, but also let a to control it

function Funca () {
FUNCB ();
Other code
}
How to define function B so that B can not only terminate B itself while it is running, but also terminate the operation of function a?

This is an unconventional question and we discuss it in two major parts. (1. Why do you do this? 2. How to achieve)

1. Obviously, this coding method has disrupted the formal principle of programming, we write the purpose of the function is to encapsulate, in order to realize the modularization of the code. If B can get a out of the way, the encoding is more than a misuse of the goto statement.

Is this necessary? Why do you have to do this ...??

The answer is as follows:
If we want to extend the prototype of the array.  For example: Define a Find method that returns the first array element that makes the function true. 1 < SCRIPT >
2//by Go_rush (Asun) @ http://ashun.cnblogs.com
3
4 Array.prototype.each = function (f) {
5 for (var i = 0; i < this. Length;i + +) f (This [i],i, this)
6}
7
8 Array.prototype.find = function (f) {
9 var result;
A. each (function (Value,index,arr) {
One if (f (value,index,arr)) result = value
12})
return result
14}
15
var arr = [1, 2, 3, 4, 5, 7, 9]
17
% function Foo (v) {//detection is not even
Return v% 2 = 0
20}
Alert (Arr.find (foo))
22
</script >


The result is another disappointment.
First: Logically, the program is wrong, because we expect to return the first even number, but the program returns the last even number.
Second: The efficiency of the program is low, even if you find the last number, he found even 4, still detect all the elements after 4. This action
is superfluous.

What do we do?  Look at line 11th in the code, if it detects that F (Value,index,arr) is true, it would be nice to interrupt the function This.each () directly. Efficiency, results, a win-win situation.

So for the question one "why do you have to do this", here, specifically to this application, there is enough reason for function B () to break function A ()

See here, you may ask: why don't you find the way to write this?

Array.prototype.find=function (f) {
for (Var i=0;i<this.length;i++) {
if (f (this[i],i,this)) return this[i]
}
}

This is not the whole world is pure.

Yes, if I was simply writing a find this would be fine, but if I'm writing a complex application right now, or writing a JS framework,

I want to implement a series of
Array.prototype.all
Array.prototype.any
Array.prototype.each
Array.prototype.map
Array.prototype.find
Array.prototype.findAll
Array.prototype.grep
Array.prototype.inject
...... Please see Prototype.js v1.4 there are 10 ways to achieve it, how can I not use the For loop for each method
Iterate over the array. I definitely want to implement a each method as a unified entry bar.

Gossip less, we see how to solve the problem:
To terminate the A function in the B function and return the result, the only way I can think of is to use the exception Try{}catch (x) {}
Implementation code
<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <script>
2//by Go_rush (Asun) @ http://ashun.cnblogs.com
3
4 var $break =new Object ()
5
6 array.prototype.each=function (f) {
7 try{
8 for (Var i=0;i<this.length;i++) {
9 try{
Ten f (this[i],i,this)
One}catch (e) {
if (e== $break) throw E
13}
14}
}catch (e) {
16}
17}
18
Array.prototype.find=function (f) {
var result;
This.each (function (Value,index,arr) {
if (f (Value,index,arr)) {
Result=value
Throw $break
25}
26})
return result
28}
29
var arr=[1,2,3,4,5,7,9]
31
function foo (v) {//detect is not even
V%2==0 return
34}
Alert (Arr.find (foo))
36
Panax Notoginseng </script>

On line 24th, if the program has found the first element that satisfies the return value of the function, it throws a custom exception that terminates the This.each ()
Run ...    Note that line 12th terminates the function by ensuring that the function throws a custom exception to continue throwing an exception up.

In the code above, the try---catch method that I used was entirely designed to solve the problem raised by this post, without any other error handling.

In this context, prototype.js, by defining two custom exception objects $break and $continue, takes care of exception handling and solves the problem posed by this post
. Enumerable object to achieve a very elegant, we may wish to experience the prototype.js in the enumerable of the beauty.

Let's see how prototype.js does it, and I'll stick it out and prototype.js the code snippet
<!--

highlighting produced by Actipro Co Dehighlighter (freeware)
http://www. codehighlighter.com/

-->var  $break     = new object ();
var  $continue  = new object ();

var enumerable = {
  each: function (iterator)  {

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.