Jérôme Jérôme - 2 months ago 11
CoffeeScript Question

Stopping a for loop until worker is done

I have made a

for
loop who call a web worker to highlight code inside
code
tag

I have made this loop, this call my worker and do the job.

highlightBase: ->
codes = document.getElementsByClassName('hljs')

if (codes)
for code in codes
HighlightWorker = new Worker('/js/highlight_worker.js')

HighlightWorker.onmessage = (event) ->
code.innerHTML = event.data

HighlightWorker.postMessage(code.textContent)


This is working well but I need to stop this loop until the worker is done.

Is this possible to stop this loop and continue it after or I need to add some
timeOut
?

Answer

Why do you need to stop the loop? It looks like you are trying to do synchronous tasks, meaning the workers do their job one after the other. But the whole thing about workers is that they are asynchronous...

I guess if you want your code to work synchronously, you need to do something like that:

    highlightBase: ->
  codes = document.getElementsByClassName('hljs')

  if (codes)
    for code in codes

        code.innerHTML = function_that_was_before_made_by_worker()

And that it is...

Comments