Home >Web Front-end >JS Tutorial >Custom method in js to implement sleep for a few seconds_javascript techniques

Custom method in js to implement sleep for a few seconds_javascript techniques

WBOY
WBOYOriginal
2016-05-16 16:42:091659browse

There is no built-in sleep method in js. If you want to sleep, you have to 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 is a supplement:

In addition to Narrative JS, jwacs (Javascript With Advanced Continuation Support) is also committed to extending JavaScript syntax to avoid writing troublesome callback functions for asynchronous calls. Sleep implemented using jwacs, the code is as follows:

Copy code The code is as follows:

function sleep(msec) {
var k = function_continuation;
setTimeout(function() { resume k ba531268c1298d89fad724a294a51e6a exitTime)
             return;
}
}

The above code does not actually cause the script interpreter to sleep, but has the side effect of quickly putting the CPU under high load. The browser may even hang in suspended animation for that period of time.

Secondly, there are smart people who use IE’s special dialog box implementation to find a way around the world. The code may be as follows:

Copy code The code is as follows:

function sleep(timeout) {
window.showModalDialog("javascript:document.writeln('3f1c4e4b6b16bbbd69b2ee476dc4f83awindow.setTimeout(function () { window.close(); }, " timeout ");2cacc6d41bbb37262a98f745aa00fbf0');");
}window.alert("before sleep ...");
sleep(2000);
window.alert("after sleep ...");

Needless to say, the disadvantage is that it is only supported by IE (IE7 cannot achieve the purpose due to security restrictions).

In addition to the above, there are also clever ideas such as using Applet or calling WScript.Sleep() of Windows Script Host. These are all last resort expedients.

Finally, smarter people have developed what may be the best solution. Let’s look at the code first:

Copy code The code is as follows:

function sleep(millis) {
var notifier = NjsRuntime.createNotifier();
setTimeout(notifier, millis);
Notifier.wait->();
}

Yes, seeing syntax like ->() is as shocking to me as just seeing Prototype’s $() function. However, this script will report a syntax error directly in the browser. In fact, they need to be precompiled into JavaScript recognized by the client browser. The compiled script is as follows:

Copy code 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.except(ex,1))
return;
}}
njf1.pf();
}

我看不懂,也不想去看懂了。这些工作全部会由 Narrative JavaScript ———— 一个提供异步阻塞功能的JS扩展帮我们实现。我们只需要编写之前那个怪异的 ->() 语法, 然后通过后台预先静态编译或者前台动态编译后执行就可以实现 sleep 的效果。
Narrative JavaScript 宣称可以让你从头昏眼花的回调函数中解脱出来,编写清晰的Long Running Tasks。目前还是 alpha 的版本,在 Example 页面上有一个移动的按钮的范例。首页上也提供了源码下载。以我薄弱的基础知识,我只能勉强的看出代码中模拟了状态机的实现,希望有精通算法的朋友能为我们解析。
最后,还是我一直以来的观点: 除非很必要,否则请保持JavaScript的简单。在JavaScript 能提供原生的线程支持之前,或许我们可以改变设计以避免异步阻塞的应用。

有bug的曲折实现

<script type"text/javascript">
/*Javascript中暂停功能的实现
Javascript本身没有暂停功能(sleep不能使用)同时 vbscript也不能使用doEvents,故编写此函数实现此功能。
javascript作为弱对象语言,一个函数也可以作为一个对象使用。
比如:

[code]
function Test(){
 alert("hellow");
 this.NextStep=function(){
 alert("NextStep");
 }
}
我们可以这样调用 var myTest=new Test();myTest.NextStep();
我们做暂停的时候可以吧一个函数分为两部分,暂停操作前的不变,把要在暂停后执行的代码放在this.NextStep中。
为了控制暂停和继续,我们需要编写两个函数来分别实现暂停和继续功能。
暂停函数如下:
*/
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);
}
/*
该函数把要暂停的函数放到数组window.eventList里,同时通过setTimeout来调用继续函数。
继续函数如下:
*/

function GoOn(ind){
 var obj=window.eventList[ind];
 window.eventList[ind]=null;
 if (obj.NextStep) obj.NextStep();
 else obj();
}
/*
该函数调用被暂停的函数的NextStep方法,如果没有这个方法则重新调用该函数。
函数编写完毕,我们可以作如下册是:
*/
function Test(){
 alert("hellow");
 Pause(this,1000);//调用暂停函数
 this.NextStep=function(){
 alert("NextStep");
 }
}
</script>
Statement:
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