How to create timed functions

I spent a while trying to figure out how to do this, and I eventually did! So I thought I’d share with you guys as many of you have helped me in the past!

Here’s an example of how to center a window after X seconds. The action could be anything, but the function below will create the timed event:


-- FUNCTION TO CENTER THE WINDOW AFTER A SET AMOUNT OF SECONDS
on CenterWindowAfter(varseconds)
	
	--Reset The Timer
	set timer to varseconds
	
	--Countdown Loop
	if timer > 0 then
		repeat while timer > 0
			delay 1
			set timer to timer - 1
		end repeat
	end if
	
	-- Action
	if timer = 0 then
		tell window "main" to center
	end if
	
end CenterWindowAfter

To call this function at any point in the script simply use:


CenterWindowAfter(5)

The snippet above will center the window after 5 seconds! :wink: Change the number to get a different countdown!

I Hope some of you will find this useful!

-Mel :wink:

Hi,

two suggestions for optimization


-- FUNCTION TO CENTER THE WINDOW AFTER A SET AMOUNT OF SECONDS
on CenterWindowAfter(varseconds)
	
	--Reset The Timer
	set timer to varseconds
	
	--Countdown Loop
	-- 	if timer > 0 then -- not needed, the repeat condition does exactly the same
	repeat while timer > 0
		delay 1
		set timer to timer - 1
	end repeat
	--	end if
	
	-- Action
	--	if timer = 0 then -- not needed, at this point the counter is always zero
	tell window "main" to center
	--	end if
	
end CenterWindowAfter

Thanks Stefan! :wink:

-Mel