First, JXA does not have window
as the global object because it is not a browser.
You can access the global object via the top level this
or, more simply, omit the global object to access the global variables and functions directly.
this.Math.sin(1)
// or
Math.sin(1)
Second, JXA has no support for setTimeout
currently.
This is the essential reason why you got the error that setTimeout
is undefined.
However, you can emulate setTimeout
with its Objective-C bridge.
This is an example implementation of setTimeout
with NSTimer
.
Note that working with NSTimer
in JXA requires to start NSRunLoop
manually.
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
}
var setTimeout = timer.bind(undefined, false)
var setInterval = timer.bind(undefined, true)
var clearTimeout = invalidate
var clearInterval = invalidate
setTimeout(function() {
console.log(123)
}, 1000)
$.NSRunLoop.currentRunLoop.runModeBeforeDate("timer", $.NSDate.distantFuture)