2015-07-10 73 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