I have tried to use a window.setTimeout
but I get an error at runtime:
Error on line 182: TypeError: window.setTimeout is not a function. (In
window.setTimeout(function(){ }, 3000);
,
window.setTimeout
is undefined) (-2700)
Can someone help me ?
There is a global delay(seconds)
function you can call.
...
delay(0.2);
...
See: https://github.com/dtinth/JXA-Cookbook/wiki/System-Events#example-of-sending-copy-command
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With