3

I have to execute a really slow (20 secs+) operation that involves the DOM. Specifically, a paper.js SVG export:

project.exportSVG({ asString: true, matchShapes: true, precision: 2 })

which repeatedly calls document.createElementNS (see here).

Since DOM operations aren't possible in workers, I can't use them to run this.

I tried using promises like this:

(new Promise((resolve, reject) => {
   console.time('export')
   var p = project;
    resolve(p.exportSVG({ asString: true, matchShapes: true, precision: 2 }));
   console.timeEnd('export')
})).then(svg => { console.log(svg) })

but it still blocks for ages.

Is there any other way I can run this without blocking for a long time?

simone
  • 4,667
  • 4
  • 25
  • 47
  • 1
    Use a Promise respective await/async. – Markus Zeller Dec 22 '20 at 08:14
  • @MarkusZeller - tried that, still blocks (document.createElementNS gets called thousands of times) – simone Dec 22 '20 at 08:28
  • onload event try to simply run a timeout to start your script, see https://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code – john Smith Dec 22 '20 at 08:31
  • 1
    One possible way would be to run your Paper.js operation on the server to decouple it from your frontend Javascript code. – sasensi Dec 22 '20 at 08:32
  • Probably you can tweak Paper.js code a little bit, maybe wrapping calls to ```document.createElementNS``` in a ```setTimeout(call, 0)``` will allow to unblock event queue a little bit. But it needs to be investigated. @simone can you setup a JSFiddle so we'll be able to reproduce those heavy DOM operations? – Monsieur Merso Dec 22 '20 at 08:43
  • 1
    You can't use a promise to make synchronous code into asynchronous code. You can use some promise techniques to change the scheduling of when code runs, but synchronous code in Javascript is still synchronous and blocking code in Javascript no matter when it runs. Promises are purely a notification system for notifying you when some other operation has told a promise that it is now resolved or rejected. They don't magically convert synchronous code into asynchronous code. https://stackoverflow.com/questions/50825071/why-is-my-chained-promise-blocking – Don Dilanga Dec 22 '20 at 08:50
  • So use asynchronous programming if you wait for some resource, or external input, a database result to not block the execution flow while waiting for the data to arrive etc.. I suggest as the other guy said to use a server side implementation. – Don Dilanga Dec 22 '20 at 08:53
  • You can try this with NodeJS. https://github.com/wilk/microjob – Don Dilanga Dec 22 '20 at 09:03

0 Answers0