js中怎么让程序暂停一段时间

JavaScript012

js中怎么让程序暂停一段时间,第1张

异步执行的函数需要使用回调来获取返回值你那种想等待回调函数执行后再把结果作为返回值的想法是无法实现,并且是极不可取的因为你并不知道需要多久该回调函数才能执行,让主线程阻塞在这儿等待不是一个正确的做法。

正确的做法还是在回调函数中获得值进行处理推荐写法:

var addre =""var bm = new BMap.Map("container")gpsxy = function (xx,yy,i,callback){//添加一个参数作为回调函数,该函数可以获取addre参数

var gpsPoint = new BMap.Point(xx,yy)

bm.clearOverlays()var marker = new BMap.Marker(gpsPoint)bm.addOverlay(marker)

bm.setCenter(gpsPoint)var gc = new BMap.Geocoder()

gc.getLocation(gpsPoint, function(rs){ var addComp = rs.addressComponents

addre = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumbercheck()

if(callback) callback(addre)//把addre传递到回调函数中,这样就可以在函数外部使用返回值了 })}

调用示范:gpsxy(10,10,1,function(addre){ alert(addre)//这儿就可以使用这个值了 })

js并没有php那种sleep函数,不过我们可以做个延时函数<br>function sleep(func,time){<br>setTimeout(typeof func==='function'&&func(),time)<br><br>}<br>调用sleep(function(){alert(1)},1000),来让js脚本延时1秒后弹出1

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

试试这个:

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. }