Invalidate NSTimer when app is not active

I’m trying to invalidate a NSTimer when app is not active:

global theTimer

on applicationWillBecomeActive:notif
	set theTimer to current application's NSTimer's scheduledTimerWithTimeInterval:theSec target:me selector:"timerDidFire:" userInfo:(missing value) repeats:true
end applicationWillBecomeActive:
	
on applicationWillResignActive:notif
	theTimer's invalidate()
end applicationWillResignActive:

Of course, it does not work…

That looks like a basic AppleScript scope issue. Try set my theTimer to…

Hi Shane,

Not better.
I’ve made a blank new app for testing with nothing else than the timer:

script AppDelegate
	property parent : class "NSObject"
	property theWindow : missing value
	property theTimer : missing value
	
	on applicationWillFinishLaunching:notif
		my timerStart:0.3
	end applicationWillFinishLaunching:
	
	on applicationShouldTerminate:sender
		return current application's NSTerminateNow
	end applicationShouldTerminate:
	
	on applicationWillBecomeActive:notif
		my timerStart:0.3
	end applicationWillBecomeActive:
	
	on applicationWillResignActive:notif
		my theTimer's invalidate()
	end applicationWillResignActive:

	 on timerStart:theSec
		set my theTimer to current application's NSTimer's scheduledTimerWithTimeInterval:theSec target:me selector:"timerDidFire:" userInfo:(missing value) repeats:true
	end timerStart:
	
	on timerDidFire:theTimer
		log "timer is running = " & (theTimer's isValid())
	end timerDidFire:
end script

The timer continues to fire when I switch from the app to Xcode or any other app.

For the invalidate() method, Apple’s documentation says : “You must send this message from the thread on which the timer was installed.”
Can it be the cause?

It looks like you’re launching two timers there, one in applicationWillFinishLaunching: and one in applicationWillBecomeActive:.

I feel sooooo stupid!

:upside_down_face: :rofl:

Ah! the magic of copy/paste!!!