2015-07-10 103 views
2

我有一個應用程序使用jQuery的迭代通過一系列的複選框。循環後響應按鈕

當它迭代時,我有一個對話框顯示打印會話的狀態。我也有一個取消按鈕來取消會話。

<input type="button" id="cancelButton" onclick="cancel()"> 

    function cancel() { 
     stop = true; 
    } 

每次迭代我檢查,如果stop是真實的,如果是這樣,我打破了循環。但問題是,如果在會話期間按取消按鈕,取消功能將只會在.each循環之後運行(這是違背目的的一種方式)。有沒有辦法讓按鈕更具響應性或更好的方法來處理這個問題?

+0

你可能不得不做這樣的事情:http://stackoverflow.com/questions/14066714/javascript-exit-from-javascript-loop-當按鈕點擊 – Pete

回答

0

在單獨的線程中運行函數?

setTimeout(function() { $('[name=check]:checked').each(function() { 
    printingFunction(); 
}); }, 1); 
+1

除非你把設置的超時鏈接在一起,我擔心這會排隊他們所有的一個一次,你的按鈕按下仍然無法工作。 – NibblyPig

+0

是啊,它仍然沒有爲我工作 –

0

您可以連鎖setTimeout s,以便可以檢查停止。你仍然需要等待當前的操作完成,但它會讓你跳出循環。

function next() 
{ 
    printingFunction(); 
    if (!stop && someOtherCheck) 
     setTimeout(function() { next(); }, 1); 
} 

next(); 
0

我不認爲你可以中斷.each環路JavaScript執行是單線程的。

但是我覺得定時器執行異步,你可以嘗試像下面取消和明確的。

像下面的邏輯可能會讓你在那裏。

var timeouts = []; 

$.each(someArray, function(index, value){ 
    timeouts.push(setTimeout(function(){ 
      console.log(index); 
    },5000*index)); 
}); 


$('#cancel-button').click(function(){ 
    $.each(timeouts, function (_, id) { 
     clearTimeout(id); 
    }); 

    timeouts = []; 
}): 

此外,你可以考慮用.index()玩,如果上面沒有幫助。

0

再試一次 - 我做了更改移位語句,將清除錯誤的IE 11:

var ele = Array.prototype.shift.call($checked); 

您需要使用的setTimeout在每個循環調用(可設定爲0),因此取消功能得到執行的機會 - 這樣的事情:

function cancel() { 
    stop = true; 
} 
function printingFunction() { 
    var x = 0; 
    while (x < 10000){ 
     x+=1; 
    } 
} 

function printLoop($checked) { 
    if (stop) { 
     console.log('Stopped - button pushed') 
    } else { 
     if ($checked.length > 0) { 
      var ele = Array.prototype.shift.call($checked); 
      printingFunction() 
     } 
     if ($checked.length > 0) { 
      setTimeout(function(){printLoop($checked)}, 0); 
     } else { 
      console.log('Stopped - array depleted') 
     } 

    } 

} 

var stop = false, 
     $checked = $('[name=check]:checked'); 

printLoop($checked) 
+0

謝謝!我嘗試使用解決方案,但爲'Array.shift($選中)'我一直得到一個錯誤,告訴我shift()不被識別(我正在使用IE11來運行我的應用程序),有沒有其他選擇?就好像一個好奇心,如果我在''printFunction()'的for循環中有'printRow()',那麼是否有模仿你的邏輯?那我不會在''printFunction()'中做遞歸調用嗎? –

+0

請注意上面的代碼編輯。你可以爲行做類似的事情 - 取決於打印功能實際上在做什麼...... – nril