0

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 ?

Endless
  • 34,080
  • 13
  • 108
  • 131
Jérôme
  • 1,966
  • 4
  • 24
  • 48

2 Answers2

1

I am not very familiar very coffeeScript but this might give you an idea.

Stoping a for loop is not possible. There are generator functions for that lazy evaluation purposes. However although you could use, i don't think you need generators here. Instead i guess promises could be very handy. You might use Promise.all(). But first you have to create a utility function to return a promise when you instantiate a worker.

function postMessageToWorker(worker,message){
  var p = new Promise((resolve,reject) => worker.onmessage = resolve);
  worker.postMessage(message);
  return p;
}

var proms = [];

if (codes)
  for (var code of codes)
    proms.push(postMessageToWorker(new Worker('/js/highlight_worker.js'), code.textContent));
Promise.all(proms).then(a => a.forEach((e,i) => codes[i].innerHTML = e.data));

Here is a plunker code for you to play.

Redu
  • 25,060
  • 6
  • 56
  • 76
0

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...

millerf
  • 686
  • 1
  • 8
  • 16