我尝试使用 awindow.setTimeout
但在运行时出现错误:
第 182 行错误:TypeError: window.setTimeout 不是函数。(在
window.setTimeout(function(){ }, 3000);
,
window.setTimeout
未定义) (-2700)
有人能帮我吗 ?
我尝试使用 awindow.setTimeout
但在运行时出现错误:
第 182 行错误:TypeError: window.setTimeout 不是函数。(在
window.setTimeout(function(){ }, 3000);
,
window.setTimeout
未定义) (-2700)
有人能帮我吗 ?
delay(seconds)
您可以调用一个全局函数。
...
delay(0.2);
...
请参阅:https ://github.com/dtinth/JXA-Cookbook/wiki/System-Events#example-of-sending-copy-command
首先,JXA 没有window
作为全局对象,因为它不是浏览器。您可以通过顶层访问全局对象,this
或者更简单地说,省略全局对象以直接访问全局变量和函数。
this.Math.sin(1)
// or
Math.sin(1)
其次,JXA 目前不支持setTimeout
。setTimeout
这是您得到未定义错误的根本原因。
但是,您可以setTimeout
使用它的 Objective-C bridge进行模拟。这是setTimeout
with的示例实现NSTimer
。请注意,NSTimer
在 JXA 中使用需要NSRunLoop
手动启动。
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)
JXA 中没有任何异步。您可以使用delay(3)
,但不会执行其他任何操作。
您可以使用 启动另一个任务$.system("yourCommand &")
,它异步运行。这是一个异步说话的小演示。它可能是另一个脚本,可以满足您的任何需求
ObjC.import("stdlib")
var app = Application.currentApplication()
app.includeStandardAdditions = true
$.system("(sleep 2;say hurry up!)&") // see the difference when you remove the &
prompt("are you ready?", "yes")
function prompt(text, defaultAnswer) {
var options = { defaultAnswer: defaultAnswer || "" }
try {
return app.displayDialog(text, options).textReturned
} catch (e) {
return null
}
}