JMichaelTX
11/30/2016 - 5:52 PM

setTimeout, setInterval, clearTimeout, and clearInterval on JXA (JavaScript for Automation) on macOS

setTimeout, setInterval, clearTimeout, and clearInterval on JXA (JavaScript for Automation) on macOS

var webpack = require('webpack')
module.exports = {
  entry: './test.js',
  output: {
    filename: './test.bundle.js',
  },
  node: {
    fs: 'empty',
  }
}
if (typeof setTimeout === 'undefined') {
  setTimeout = require('./jxa-timeout').setTimeout
  clearTimeout = require('./jxa-timeout').clearTimeout
}

var test = require('tape')

test('setTimeout', function (t) {
  console.log(setTimeout)
  setTimeout(function() {
    console.log(123)
    t.end()
  }, 50)
})

module.exports = undefined

if (setTimeout.run) setTimeout.run()
{
  "scripts": {
    "test": "webpack --display-modules && osascript test.bundle.js"
  },
  "dependencies": {
    "tape": "^4.6.3",
    "webpack": "^2.1.0-beta"
  }
}
if (typeof exports === 'undefined') exports = {}

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)
}

function run() {
  $.NSRunLoop.currentRunLoop.runModeBeforeDate("timer", $.NSDate.distantFuture)
}

var setTimeout = timer.bind(undefined, false)
var setInterval = timer.bind(undefined, true)
var clearTimeout = invalidate
var clearInterval = invalidate
setTimeout.run = setInterval.run = run

exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimeout = clearTimeout
exports.clearInterval = clearInterval
exports.run = run