diff --git a/svgnest.js b/svgnest.js index 187356ad..7ef8d8e8 100644 --- a/svgnest.js +++ b/svgnest.js @@ -42,6 +42,7 @@ var best = null; var workerTimer = null; var progress = 0; + var activeWorkers = []; // Track active workers this.parsesvg = function(svgstring){ // reset if in progress @@ -338,6 +339,9 @@ evalPath: 'util/eval.js' }); + // Track this worker + activeWorkers.push(p); + p.require('matrix.js'); p.require('geometryutil.js'); p.require('placementworker.js'); @@ -541,6 +545,9 @@ evalPath: 'util/eval.js' }); + // Track this worker too + activeWorkers.push(p2); + p2.require('json.js'); p2.require('clipper.js'); p2.require('matrix.js'); @@ -582,11 +589,25 @@ displayCallback(); } self.working = false; + + // Remove completed workers from tracking + var index = activeWorkers.indexOf(p); + if (index > -1) activeWorkers.splice(index, 1); + index = activeWorkers.indexOf(p2); + if (index > -1) activeWorkers.splice(index, 1); }, function (err) { console.log(err); + // Remove failed workers from tracking + var index = activeWorkers.indexOf(p); + if (index > -1) activeWorkers.splice(index, 1); + index = activeWorkers.indexOf(p2); + if (index > -1) activeWorkers.splice(index, 1); }); }, function (err) { console.log(err); + // Remove failed worker from tracking + var index = activeWorkers.indexOf(p); + if (index > -1) activeWorkers.splice(index, 1); }); } @@ -813,7 +834,23 @@ this.working = false; if(workerTimer){ clearInterval(workerTimer); + workerTimer = null; + } + + // Terminate all active workers + for(var i = 0; i < activeWorkers.length; i++){ + try { + if(activeWorkers[i] && typeof activeWorkers[i].kill === 'function'){ + activeWorkers[i].kill(); + } + } catch(e) { + // Ignore errors when terminating workers + console.log('Error terminating worker:', e); + } } + + // Clear the active workers array + activeWorkers = []; }; }