Skip to content

Instantly share code, notes, and snippets.

@notoriousb1t
Last active July 18, 2019 12:11
Show Gist options
  • Save notoriousb1t/3fd38c7c4429feece8a234003cf22c35 to your computer and use it in GitHub Desktop.
Save notoriousb1t/3fd38c7c4429feece8a234003cf22c35 to your computer and use it in GitHub Desktop.
Request Idle Callback Example
<div id="app">
<div>
<button @click="task.start()">Start</button>
<button @click="task.stop()">Stop</button>
</div>
<textarea class="log">{{log}}</textarea>
</div>
console.clear();
new Vue({
el: '#app',
data: function() {
return {
log: '',
task: backgroundTask({
name: "Test Task",
interval: 5000,
self: this,
action: this.action
})
}
},
mounted() {
this.task.start();
},
methods: {
action() {
this.log += 'background task ran\n';
}
}
})
function backgroundTask(options) {
var idleId, timeoutId;
function start() {
if (timeoutId || idleId) {
stop();
}
log("started");
(function taskScript() {
timeoutId = 0;
idleId = (idleId || requestIdleCallback(function() {
idleId = 0;
timeoutId = setTimeout(taskScript, options.interval);
options.action.call(options.self);
}));
}())
log("scheduled");
}
function stop() {
log("stopping");
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = 0;
}
if (idleId) {
cancelIdleCallback(idleId);
idleId = 0;
}
log("stopped");
}
function log(message) {
console.log((options.name || "anonymous") + ": " + message);
}
return {
start: start,
stop: stop
};
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
html, body {
font-family: Arial;
height: 100%;
width: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
body {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
#app {
height: 50vh;
width: 100%;
max-width: 50vw;
}
button {
margin: .5rem;
padding: .35rem 1rem;
}
.log {
width: 100%;
height: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment