HTML5 WebWorkers Time Function

I'm trying to get the WebWorker to count to 100 and update the div with the value I, currently the div just updates straight to 100 and seems to ignore the spacing ....

JavaScript (web search file):

 self.addEventListener('message', function (e) {

        switch (e.data) {

            case 'Hi Worker':
                postMessage('Hi Boss');
                break

            case 'Count to 100':
                var i;
                for (i = 0; i < 100; i++) {
                    setInterval(postMessage(i + 1), 1000);
                }

                break;
            default:
                self.postMessage("Not sure how to help with that");
        }

    }, false);

      

Main file:

           <script>
            var worker = new Worker('worker.js');

            worker.addEventListener('message', function (e) {
                console.log("worker said: " + "'" + e.data + "'");
                document.getElementById("workerComms").textContent = "worker said: " + e.data;
            }, false);       

        </script>
    </head>
    <body>

        <button onclick="worker.postMessage('Hi Worker');return false;">Say 'Hi Worker'</button>
            <button onclick="worker.postMessage('Count to 100');return false;">Count to 100</button>

            <div id="workerComms">Things workers say...</div>

      

+3


source to share


1 answer


setInterval(postMessage(i + 1), 1000);

calls postMessage(i + 1)

and then passes the return value to setInterval

, just like foo(bar())

calling bar

and passes the return value to foo

.

Instead

  • You want to pass a reference to a function setInterval

  • You want to use setTimeout

    , notsetInterval

  • You want to change the timeout because otherwise they will all be stacked on top of each other in a second

Something like:



for (i = 1; i <= 100; i++) {
    setTimeout(postMessage.bind(window, i), 1000 * i);
}

      

will probably do it. This amounts to 100 timers at one second intervals. It uses postMessage.bind(window, i)

to create a function which is a call postMessage

to this

set to window

, and is transmitted in i

the first argument. I did i

from 1

to 100

, not from 0

to 99

, so as not to add to it 1

in both places where I used it.

Alternatively, you can omit the loop entirely for

and use setInterval

either chaining with chaining setTimeout

. Here setInterval

:

var i = 0;
var timer = setInterval(function() {
    postMessage(++i);
    if (i >= 100) {
        clearInterval(timer);
    }
}, 1000);

      

+2


source







All Articles