Last active
May 2, 2017 07:22
-
-
Save AStaroverov/ddface9819748924d609105d97331826 to your computer and use it in GitHub Desktop.
Scheduler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function importScript (path) { | |
var tag = 'script' | |
var scriptTag = document.createElement(tag), | |
firstScriptTag = document.getElementsByTagName(tag)[0]; | |
scriptTag.src = path | |
firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); | |
} | |
importScript('https://rawgit.com/AStaroverov/Scheduler/master/Scheduler.js') | |
if (!window.setImmediate) { | |
importScript('https://cdnjs.cloudflare.com/ajax/libs/setImmediate/1.0.5/setImmediate.min.js') | |
} | |
var resolved = Promise.resolve(); | |
function nextTick (fn) { | |
resolved.then(fn) | |
} | |
function getTaskWrapperFunction (task) { | |
const { priority } = task | |
switch (true) { | |
case priority < 200: { | |
return // sync perform | |
} | |
case priority < 600: { | |
return nextTick | |
} | |
case priority < 800: { | |
return setImmediate | |
} | |
default: { | |
return setTimeout | |
} | |
} | |
} | |
var raf = window.requestAnimationFrame | |
function doubleRaf (cb) { return raf(() => raf(cb)) } | |
function longRaf (cb) { return setTimeout(cb, 16 * 4) } | |
function getFrameFunction (tasksForFrame) { | |
var countTasks = tasksForFrame.length | |
switch (true) { | |
case countTasks < 30: { | |
return raf | |
} | |
case countTasks < 100: { | |
return doubleRaf | |
} | |
default: { | |
return longRaf | |
} | |
} | |
} | |
// 3 sec for start chrome profiler :) | |
setTimeout(() => { | |
var sch = new Scheduler.default({ getTaskWrapperFunction, getFrameFunction }) | |
var i = 1000 | |
while (i--) { | |
(function (id) { | |
var priority = id | |
sch.addTask({ | |
handler () { | |
var div = document.createElement('div') | |
div.innerHTML = `some text task ${priority}` | |
document.body.appendChild(div) | |
console.log() | |
}, | |
priority | |
}) | |
})(i) | |
} | |
var i = 200 | |
while (i--) { | |
(function (id) { | |
var priority = parseInt(id * Math.random() * 10) | |
sch.subscribeTask({ | |
handler () { | |
var div = document.createElement('div') | |
div.innerHTML = `some text subscribeTask ${priority}` | |
document.body.appendChild(div) | |
}, | |
priority | |
}) | |
})(i) | |
} | |
sch.start() | |
setTimeout(() => { | |
sch.stop() | |
console.log(sch) | |
}, 5000) | |
}, 3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can run inside latest chrome