requestIdleCallback()による協調的バックグラウンド処理の実現 / requestIdleCallback()

requestIdleCallback()による協調的バックグラウンド処理の実現 / requestIdleCallback()

F7dd7b43a0cc6c063f7d98ba23a1d359?s=128

久保田光則

July 24, 2017
Tweet

Transcript

  1. 10.

    requestIdleCallback(function (deadline) { while (deadline.timeRemaining() > 0) { doSomething(); }

    // ·ͩ΍Γ͍ͨλεΫ͕࢒͍ͬͯΔ৔߹ requestIdleCallback(callback); });
  2. 11.
  3. 12.
  4. 16.

    // ΢ΣϒϖʔδଆͷJS <script> var worker = new Worker(‘task.js’); </script> //

    task.js … // ϫʔΧʔεϨουͰॲཧ͢ΔίʔυΛॻ͘
  5. 17.

    // ΢ΣϒϖʔδଆͷJS <script> var worker = new Worker(‘task.js’); worker.postMessage({msg: ‘hello’});

    </script> // task.js self.addEventListener(‘message’, function(e) { // e.data.msg === ‘hello’ });
  6. 18.

    // ΢ΣϒϖʔδଆͷJS <script> var worker = new Worker(‘task.js’); worker.addEventListener(‘message’, callback);

    worker.postMessage({msg: ‘hello’}); </script> // task.js self.addEventListener(‘message’, function(e) { self.postMessage({msg: e.data.msg}); });
  7. 25.

    // ΠϯϥΠϯϫʔΧʔͷྫ var bb = new BlobBuilder(); bb.append("onmessage = function(e)

    { postMessage('msg from worker'); }"); var blobURL = window.URL.createObjectURL(bb.getBlob()); var worker = new Worker(blobURL);
  8. 31.

    function bgtask(deadline) { while (deadline.timeRemaining() > 0) { // 10-20msඵఔ౓ҎԼʹ͢Δ

    doMicroTask(); } requestIdelCallback(bgtask); }); requestIdleCallback(bgtask);
  9. 32.

    requestIdleCallback(function(deadline) { while (deadline.timeRemaining() > 0) { var result =

    doSomething(); // ಉظతʹDOMૢ࡞͸͠ͳ͍Α͏ʹ͢Δ requestAnimationFrame(function() { document.body.querySelector(‘#hoge’) = result; }); } });
  10. 33.
  11. 35.

    function runInIdle(it) { requestIdleCallback(function(deadline) { var val = it.next(); while

    (!val.done) { if (deadline.timeRemaining() <= 0) { runInIdle(it); return; } val = it.next(); } }); }
  12. 36.

    // όοΫάϥ΢ϯυͰfizzbuzz͢Δྫ function* fizzbuzz() { for (var i = 0;;i++)

    { yield; // ←͜͜ͰॲཧΛ෼ׂ if (i % 15 = 0) output(‘FizzBuzz’); else if (i % 3 == 0) output(‘Fizz’); else if (i % 5 == 0) output(‘Buzz’); else output(i); } }; runInIdle(fizzbuzz());