4

我尝试使用 awindow.setTimeout但在运行时出现错误:

第 182 行错误:TypeError: window.setTimeout 不是函数。(在

window.setTimeout(function(){

}, 3000);

,window.setTimeout未定义) (-2700)

有人能帮我吗 ?

4

3 回答 3

7

delay(seconds)您可以调用一个全局函数。

...
delay(0.2);
...

请参阅:https ://github.com/dtinth/JXA-Cookbook/wiki/System-Events#example-of-sending-copy-command

于 2017-05-31T07:46:44.143 回答
5

首先,JXA 没有window作为全局对象,因为它不是浏览器。您可以通过顶层访问全局对象,this或者更简单地说,省略全局对象以直接访问全局变量和函数。

this.Math.sin(1)
// or
Math.sin(1)

其次,JXA 目前不支持setTimeoutsetTimeout这是您得到未定义错误的根本原因。

但是,您可以setTimeout使用它的 Objective-C bridge进行模拟。这是setTimeoutwith的示例实现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)
于 2016-12-11T14:58:49.437 回答
3

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
  }
}
于 2016-06-15T18:16:54.190 回答