Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimout with Javascript for automation

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 ?

like image 817
Mermoz Avatar asked Dec 05 '22 17:12

Mermoz


2 Answers

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

like image 164
konrad Avatar answered Dec 23 '22 13:12

konrad


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)
like image 26
Kaito Udagawa Avatar answered Dec 23 '22 11:12

Kaito Udagawa