關於JS控制碼暫停實現方法分享

來源:互聯網
上載者:User

方法一:這是在網上找的一個方法,可以用。但說實話,這個方法我不怎麼明白。。。寫得好複雜。這樣做跟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);
}

以上僅供大家參考,歡迎吐槽!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.