方法一:这是在网上找的一个方法,可以用。但说实话,这个方法我不怎么明白。。。写得好复杂。这样做跟setTimeout能有多大区别?
实现代码如下:

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 + ")" , iMinSecond);
}
function GoOn(ind) {
var obj = window.eventList[ind];
window.eventList[ind] = null;
if (obj.NextStep) obj.NextStep();
else obj();
}
function testJsStop() {
alert( "1");
Pause( this, 3000);
this.NextStep = function () {
alert( "2");
}
}

方法二:这也是在网上找的,可以用。它的原理是先弹出一个窗口,因为JS在弹出窗口时,代码会在当前位置暂停执行。等过了一段时间后再执行关闭窗口函数,代码继续执行。这中方法非常简单,但令人讨厌的是它会弹出一个窗口。。。
实现代码如下:

function pause(numberMillis) {
addcloud();
var dialogScript = 'window.setTimeout(' + ' function () { $("#bgDiv").remove(); }, ' + numberMillis + ');';
var result = window.showModalDialog('javascript:document.writeln(' + '"<script>' + dialogScript + '<' + '/script>")' );
}
function test() {
var a = 0;
alert(a);
pause(5000);
a = 999;
alert(a);
}

方法三:这个方法是我自己写的。因为我要实现的功能比较复杂,要循环调用getpath()方法。而前面的两种方法都只能应用在顺序执行的代码段中,无法控制循环。在这里我采用了前后台结合的方法。在前台通过Ajax调用后台方法,直接将线程挂起1s,成而实现JS代码强制暂停。
前台JS:
实现代码如下:

function getpath() {
var time = 1000;
$.ajaxSettings.async = false;
$.getJSON( "../Actions/TspHandler.ashx?rKey=" + parseInt(Math.random() * 999 + 1).toString() + "&opKey=Sleep"
+ "&Time=" + time,
null,
function (json) {
});
..........
}

后台ashx:
实现代码如下:

if (methodname == "Sleep" )//休眠
{
int time = int .Parse(req["Time"].ToString());
System.Threading. Thread.Sleep(time);
}

以上仅供大家参考,欢迎吐槽!

以上就是【关于JS控制代码暂停的实现方法分享】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论