简体   繁体   中英

How do i implement multi-threading in my JavaScript?

My website allow users to record canvas and also draw on the canvas at the same time. if users start recording the canvas and also start to draw on the canvas the drawing on the canvas it will start to lagg. I am told that multi-threading web workers should be able to solve the problem. however I am not sure how should I start.

Could someone guide me please? what should I put in postmessage/onmessage?

var recordUrl;
var audioUrl;
var audioStream;
var audiorecorder;
var elementToShare = document.getElementById("elementToShare");
var recorder = RecordRTC(elementToShare, {
    type: 'canvas'
});

document.getElementById('start').onclick = function() {

    /*
    <script id="worker" type="javascript/worker">

    <!--M KY -->
        multithreading
        var blob = new Blob([document.getElementById('worker').textContent]);
        var worker = new Worker(window.webkitURL.revokeObjectURL(blob));
        URL.revokeObjectURL(blob);
        return worker;

        worker.onmessage = function(event) {

        }

        worker.postnmessage = function(event) {

        }
        */
    $('#record').trigger('click');

    if (!audioStream)
        navigator.getUserMedia(audioConstraints, function(stream) {
            if (window.IsChrome) stream = new window.MediaStream(stream.getAudioTracks());
            audioStream = stream;

            // "audio" is a default type
            audiorecorder = window.RecordRTC(stream, {
                type: 'audio',
                bufferSize: typeof params.bufferSize == 'undefined' ? 16384 : params.bufferSize,
                sampleRate: typeof params.sampleRate == 'undefined' ? 44100 : params.sampleRate,
                leftChannel: params.leftChannel || false,
                disableLogs: params.disableLogs || false
            });
            audiorecorder.startRecording();
        }, function() {});
    else {
        audio.src = URL.createObjectURL(audioStream);
        audio.muted = true;
        audio.play();
        if (audiorecorder) audiorecorder.startRecording();
    }

    window.isAudio = true;

    recorder.startRecording();
    document.getElementById('start').disabled = true;
    setTimeout(function() {
        document.getElementById('stop').disabled = false;
    }, 1000);
//worker.terminate();
// }
};

canvas code

<div id="cover">
                                <!-- <canvas id="fakecanvas" width="890" height="1267" style="z-index: 2; position: absolute;left:18%"></canvas> -->
                                <canvas id="canvas" width="890" height="1267" style="z-index: 1; border:1px solid black; position: absolute;"></canvas>
                            </div>                          
                        </div>
                    </section>                  
                    <section id="section-2">
                        <div style="width: 100%; height:5%; float:left;">
                        <a id="capture2" onclick="capFunction2();">
                            <input type="image" name="screenshot2" value="Save This Page" style="float: right; width:25px; height:25px;" src="img/camera.png">
                        </a>
                        <script>
                        function downloadCanvas2(link, canvasId, filename) {
                            html2canvas([document.getElementById(canvasId)], {
                                onrendered: function(cvs2) {
                                    //var canvasData = cvs2.toDataURL('image/png');
                                    var link = document.createElement("a");
                                    link.href = cvs2.toDataURL();
                                    link.download = filename;
                                    link.click();
                                }
                            });
                        }

                        document.getElementById('capture2').addEventListener('click', function() {
                            var currentTime2 = new Date().YYYYMMDDHHMMSS();
                            downloadCanvas2(this, 'viewer2', currentTime2 + '.jpg');    
                            }, false);
                        </script>

javaScript is single threaded. There is only one javascript thread per window which is frequently termed as Browser UI Thread ("thread" is not necessarily accurate for all browsers).

Question :

How does asynchronous events like ajax,setTimeout occurs?

A browser comes with an inner loop called Event Loop, which checks the queue and process & execute it.So they run only when there is a opening in execution. I can write a long article on how this work but that is out of the context.

So what is the solution? Web workers?

Yes,it can accomplish some of the feature which a multithreading does. But it comes with limitations

  • It cannot acces DOM.

  • They cannot access global variable or js functions in main page.

  • Access to some objects like window,document & parents is restricted

So even if you want to acheive multithreading with web workers you may need to modify your code and make it event driven programming rather than data driven coding.

Hope it will be useful for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM