Heim  >  Artikel  >  Web-Frontend  >  关于JS控制代码暂停的实现方法分享_javascript技巧

关于JS控制代码暂停的实现方法分享_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:49:25957Durchsuche

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

复制代码 代码如下:

function Pause(obj, iMinSecond) {
if (window.eventList == null ) window.eventList = new Array();
var ind = -1;
for (var i = 0; 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>")' ); <BR>} <BR>function test() { <BR>var a = 0; <BR>alert(a); <BR>pause(5000); <BR>a = 999; <BR>alert(a); <BR>} <BR></script>

方法三:这个方法是我自己写的。因为我要实现的功能比较复杂,要循环调用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);
}

以上仅供大家参考,欢迎吐槽!
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn