js怎样实现暂停

JavaScript012

js怎样实现暂停,第1张

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 = 0i <window.eventList.lengthi++) {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")

Pause(this, 3000)// 调用暂停函数

this.NextStep=function(){

alert("NextStep")

}

}

Test()

1、跳出循环用break语句就可以实现。打开hbuilder软件,创建一个点击按钮标签和用于显示循环内容的div标签:

2、在scrip标签里,创建点击触发循环的方法,循环里当循环到3的时候,用break语句跳出循环体,在button标签上添加点击myFunction()函数:

3、按下crtl+s保存后,使用浏览器打开,点击按钮可以发现按钮下方只打印出从0-2的内容,这就表示成功使用break跳出循环体了:

其实我们可以这样想:浏览器是单线程的,那么我们只要在暂停的地方做三秒其他的事情不就达到了暂停的效果吗。

试试这个:

1. //js暂停函数

2. function Pause(obj,iMinSecond){

3.if (window.eventList==null) window.eventList=new Array()

4.var ind=-1

5.for (var i=0i<window.eventList.lengthi++){

6.if (window.eventList[i]==null) {

7. window.eventList[i]=obj

8. ind=i

9. break

10. }

11. }

12.if (ind==-1){

13.ind=window.eventList.length

14.window.eventList[ind]=obj

15.}

16. setTimeout("GoOn(" + ind + ")",iMinSecond)

17. }

18.

19. //js继续函数

20. function GoOn(ind){

21. var obj=window.eventList[ind]

22. window.eventList[ind]=null

23. if (obj.NextStep) obj.NextStep()

24. else obj()

25. }

//js暂停函数

function Pause(obj,iMinSecond){

if (window.eventList==null) window.eventList=new Array()

var ind=-1

for (var i=0i<window.eventList.lengthi++){

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)

}

//js继续函数

function GoOn(ind){

var obj=window.eventList[ind]

window.eventList[ind]=null

if (obj.NextStep) obj.NextStep()

else obj()

}

使用方法很简单:

Java代码

1. function testJsStop(){

2. alert("1")

3. Pause(this,3000)

4. this.NextStep=function(){

5. alert("2")

6. }

7. }