Skip to content

Instantly share code, notes, and snippets.

@umireon
Created November 30, 2016 17:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umireon/d1d449be666053b005e48db48aad6c46 to your computer and use it in GitHub Desktop.
Save umireon/d1d449be666053b005e48db48aad6c46 to your computer and use it in GitHub Desktop.
setTimeout, setInterval, clearTimeout, and clearInterval on JXA (JavaScript for Automation) on macOS
if (typeof exports === 'undefined') exports = {}
function timer (repeats, func, delay) {
var args = Array.prototype.slice.call(arguments, 2, -1)
args.unshift(this)
var boundFunc = func.bind.apply(func, args)
var operation = $.NSBlockOperation.blockOperationWithBlock(boundFunc)
var timer = $.NSTimer.timerWithTimeIntervalTargetSelectorUserInfoRepeats(
delay / 1000, operation, 'main', null, repeats
)
$.NSRunLoop.currentRunLoop.addTimerForMode(timer, "timer")
return timer
}
function invalidate(timeoutID) {
$(timeoutID.invalidate)
}
function run() {
$.NSRunLoop.currentRunLoop.runModeBeforeDate("timer", $.NSDate.distantFuture)
}
var setTimeout = timer.bind(undefined, false)
var setInterval = timer.bind(undefined, true)
var clearTimeout = invalidate
var clearInterval = invalidate
setTimeout.run = setInterval.run = run
exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimeout = clearTimeout
exports.clearInterval = clearInterval
exports.run = run
{
"scripts": {
"test": "webpack --display-modules && osascript test.bundle.js"
},
"dependencies": {
"tape": "^4.6.3",
"webpack": "^2.1.0-beta"
}
}
if (typeof setTimeout === 'undefined') {
setTimeout = require('./jxa-timeout').setTimeout
clearTimeout = require('./jxa-timeout').clearTimeout
}
var test = require('tape')
test('setTimeout', function (t) {
console.log(setTimeout)
setTimeout(function() {
console.log(123)
t.end()
}, 50)
})
module.exports = undefined
if (setTimeout.run) setTimeout.run()
var webpack = require('webpack')
module.exports = {
entry: './test.js',
output: {
filename: './test.bundle.js',
},
node: {
fs: 'empty',
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment