【发布时间】:2018-02-24 03:28:36
【问题描述】:
我为函数按顺序运行创建了一个系统。
我介绍了waitAndExecute 在 prev 函数完成后运行一个函数。 BUILT jsfiddle 展示了waitAndExecute 函数的工作原理。 (https://jsfiddle.net/wjuj7o8h/2/)
它在某些功能上运行良好(在 jsfiddle startTest1 中)。 但是在引入 for 循环之后它永远不会工作(在 jsfiddle startTest2 中)。
HTML
<textarea id="textarea" rows="25" cols="50">
</textarea>
<button id="startTest"> start Testing </button>
JAVASCRIPT
lastIndex = 0;
function waitAndExecute(condition, callback, interval = 30, maxcount = 100, errorcallback = function(){ alert("time limit");}){
var Interval_count = 0;
var Interval_ID = setInterval(function(){
if(condition()){
callback();
clearInterval(Interval_ID);
}
Interval_count += 1;
if(Interval_count > maxcount){
clearInterval(Interval_ID);
errorcallback();
}
},interval);
}
function compareTwo(x, y){
return x == y;
}
$('#startTest').click( function(){
var a = 1;
var syncMonitor = 0;
for(var i = 1; i < 10; i++){
waitAndExecute(
function(){
return compareTwo(lastIndex, i-1);
},
function(){
setTimeout(function(){
a = i * 100 + 1;
document.getElementById("textarea").value = document.getElementById("textarea").value + a.toString();
syncMonitor = 1;
},30);
waitAndExecute(function(){ return syncMonitor;},function(){
syncMonitor = 0;
setTimeout(function(){
a = i * 100 + 2;
document.getElementById("textarea").value = document.getElementById("textarea").value + a.toString();
syncMonitor = 1;
lastIndex = i;
},30);
})
});
}
});
我想要的结果
101 102 (30ms)
201 202 (60ms)
301 302 (90ms)
401 402 (120ms)
501 502 (150ms)
601 602 (180ms)
701 702 (210ms)
801 802 (240ms)
901 902 (270ms)
当前结果:
提醒时间限制
问题:
如何更轻松地构建此系统或如何解决此问题?
【问题讨论】:
标签: javascript jquery html synchronization closures