Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

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

久保田光則

July 24, 2017
Tweet

More Decks by 久保田光則

Other Decks in Programming

Transcript

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

    // ·ͩ΍Γ͍ͨλεΫ͕࢒͍ͬͯΔ৔߹ requestIdleCallback(callback); });
  2. // ΢ΣϒϖʔδଆͷJS <script> var worker = new Worker(‘task.js’); </script> //

    task.js … // ϫʔΧʔεϨουͰॲཧ͢ΔίʔυΛॻ͘
  3. // ΢ΣϒϖʔδଆͷJS <script> var worker = new Worker(‘task.js’); worker.postMessage({msg: ‘hello’});

    </script> // task.js self.addEventListener(‘message’, function(e) { // e.data.msg === ‘hello’ });
  4. // ΢Σϒϖʔδଆͷ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}); });
  5. // ΠϯϥΠϯϫʔΧʔͷྫ 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);
  6. function bgtask(deadline) { while (deadline.timeRemaining() > 0) { // 10-20msඵఔ౓ҎԼʹ͢Δ

    doMicroTask(); } requestIdelCallback(bgtask); }); requestIdleCallback(bgtask);
  7. requestIdleCallback(function(deadline) { while (deadline.timeRemaining() > 0) { var result =

    doSomething(); // ಉظతʹDOMૢ࡞͸͠ͳ͍Α͏ʹ͢Δ requestAnimationFrame(function() { document.body.querySelector(‘#hoge’) = result; }); } });
  8. function runInIdle(it) { requestIdleCallback(function(deadline) { var val = it.next(); while

    (!val.done) { if (deadline.timeRemaining() <= 0) { runInIdle(it); return; } val = it.next(); } }); }
  9. // όοΫάϥ΢ϯυͰ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());