javascript如何实现暂停功能

内容摘要
本文实例讲述了JS实现的自定义网页拖动类。分享给大家供大家参考,具体如下:

Javascript本身没有暂停功能(sleep不能使用)同时 vbscript也不能使用doEvents,故编写此函数实现此功
文章正文

本文实例讲述了JS实现的自定义网页拖动类。分享给大家供大家参考,具体如下:
Javascript本身没有暂停功能(sleep不能使用)同时 vbscript也不能使用doEvents,故编写此函数实现此功能。
javascript作为弱对象语言,一个函数也可以作为一个对象使用。
比如:

1
2
3
4
5
6
function Test(){
 alert("hellow");
 this.NextStep=function(){
 alert("NextStep");
 }
}

我们可以这样调用 var myTest=new Test();myTest.NextStep(); 
我们做暂停的时候可以吧一个函数分为两部分,暂停操作前的不变,把要在暂停后执行的代码放在this.NextStep中。
为了控制暂停和继续,我们需要编写两个函数来分别实现暂停和继续功能。
暂停函数如下:   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<script language="javascript">
  function sleep(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 + ")",iMinSecond);
  }
  /*
  该函数把要暂停的函数放到数组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");
   sleep(this,3000);//调用暂停函数
   this.NextStep=function(){
   alert("NextStep");
   }
  }
Test();
  </script>

 希望本文对大家学习javascript程序设计有所帮助。


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!