关于JS控制代码暂停的实现⽅法分享
⽅法⼀:这是在⽹上的⼀个⽅法,可以⽤。但说实话,这个⽅法我不怎么明⽩。。。写得好复杂。这样做跟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);
}
以上仅供⼤家参考,欢迎吐槽!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。