Created
January 13, 2019 06:09
-
-
Save andyholmes/582c29facbdbe67048c831a6370173eb to your computer and use it in GitHub Desktop.
Simple ports of setTimeout and setInterval in GJS
This file contains hidden or 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
#!/usr/bin/env gjs | |
const GLib = imports.gi.GLib; | |
/** | |
* https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval | |
* https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval | |
*/ | |
window.setInterval = function(func, delay, ...args) { | |
return GLib.timeout_add(GLib.PRIORITY_DEFAULT, delay, () => { | |
func(...args); | |
return GLib.SOURCE_CONTINUE; | |
}); | |
}; | |
window.clearInterval = GLib.source_remove; | |
/** | |
* https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout | |
* https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout | |
*/ | |
window.setTimeout = function(func, delay, ...args) { | |
return GLib.timeout_add(GLib.PRIORITY_DEFAULT, delay, () => { | |
func(...args); | |
return GLib.SOURCE_REMOVE; | |
}); | |
}; | |
window.clearTimeout = GLib.source_remove; | |
/** | |
* Example | |
*/ | |
Promise.delay = (delay) => new Promise(resolve => setTimeout(resolve, delay)); | |
async function example() { | |
try { | |
log('wait a second...'); | |
await Promise.delay(1000); | |
log('starting first timer'); | |
let intervalId1 = setInterval(() => log('timer1'), 1000); | |
let timeoutId1 = setTimeout(() => clearInterval(intervalId1), 6000); | |
log('starting second timer'); | |
let intervalId2 = setInterval(log, 500, 'timer2'); | |
let timeoutId2 = setTimeout(() => clearInterval(intervalId2), 3000); | |
} catch (e) { | |
logError(e); | |
} | |
} | |
example(); | |
// Need an event loop running | |
let loop = GLib.MainLoop.new(null, false); | |
loop.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment