0
我需要在socket.io事件中使用從前端傳遞的不同變量創建同一個函數的多個實例。我還需要這些變量對另一個socket.io事件可見,以便我可以從前端點擊中停止該功能。我有一切工作很好,但我只能用一個實例設置變量'bigLoop',並需要它爲多個實例工作。我需要所有的循環能夠運行並且彼此獨立。每次在Socket.io事件中創建具有不同變量的相同函數的多個實例
插座事件:
//this is what I have so far and it works great, I can start and stop at any time. And I know bigLoop is global
io.on('connection', function(connect) {
//create new loop
connect.on('createLoop', function(data) {
bigLoop = new syncLoop(data.total, function(){}, function(){});
});
//end loop
connect.on('endLoop', function(data) {
bigLoop.break(true);
});
});
//this is what I would like passing an array of multiple variables from the front end and creating a new syncLoop for each variable
//create new loop
connect.on('createLoop', function(data) {
//save array to variable
var newNames = data.array;
//for each variable create new syncLoop
newNames.forEach(function(newLoops) {
newloops = new syncLoop(data.total, function(){}, function() {});
});
});
//end loop
connect.on('endLoop', function(data) {
//save array to variable
var endNames = data.array;
//for each variable end loop
endNames.forEach(function(endLoops){
endLoops.break(true);
});
});
//syncLoop function, for process and exit I have a lot more going on but did not want to write it
function syncLoop(iterations, process, exit){
\t var \t index = 0,
\t done = false,
\t shouldExit = false;
loop = {
next:function(){
if(done){
if(shouldExit && exit){
return exit(); // Exit if we're done
}
}
// If we're not finished
if(index < iterations){
index++; // Increment our index
process(loop); // Run our process, pass in the loop
// Otherwise we're done
} else {
done = true; // Make sure we say we're done
if(exit) exit(); // Call the callback on exit
}
},
iteration:function(){
return index - 1; // Return the loop number we're on
},
break:function(end){
done = true; // End the loop
shouldExit = end; // Passing end as true means we still call the exit callback
}
};
loop.next();
return loop;
};
我已經嘗試了很多不同的東西,我不能得到這個工作。我感謝任何幫助。謝謝。
謝謝!!!!我只是調整了代碼,它正在啓動和停止循環和多個循環。 – jonhill13
沒問題,請將我的答案標記爲接受以幫助其他人:) – qxz
我做到了,但我還沒有15的聲望。它被記錄但不公開顯示。我會盡力提升自己的聲譽,然後再次點擊。謝謝。 – jonhill13