Progress Bar, repeat while routine

I am trying to build a simple app that monitors the files in a folder, returns their count, and returns a progress bar indicating the number of files left to process. I have an external application that moves files in and out of this folder. Setting the count of a field is no problem but when I try to do a repeat routine and update the count the application is grayed out in the background and I cannot bring it to the foreground. Without the repeat routine the app comes to the foreground. How can I update my progress bar while the repeat loop checks if the condition is true?

Any help would be great.

Thanks

Brad

Here is my code:

on launched theObject
	set watchfolder to "MacintoshHD:Users:username:Desktop:monitor:"
	
	set visible of window "Monitor" to true
	set the startingCount to countWatchfolder(watchfolder)
	
	set maximum value of progress indicator "bar" of window "Monitor" to startingCount
	set content of progress indicator "bar" of window "Monitor" to 0
	set indeterminate of progress indicator "bar" of window "Monitor" to false
	
	start progress indicator "bar" of window "Monitor"
	start progress indicator "spinner" of window "Monitor"
	
	set currentCount to countWatchfolder(watchfolder)
	
	repeat while currentCount is greater than 0
		try
			set currentCount to countWatchfolder(watchfolder)
			set content of text field "count" of window "Monitor" to currentCount
			set processedCount to (startingCount - currentCount)
			set content of progress indicator "bar" of window "Monitor" to processedCount
			
		end try
		update window "Monitor"
		
	end repeat
	quit
end launched

on countWatchfolder(watchfolder)
	set theFolderItems to list folder watchfolder without invisibles
	set theCount to count of theFolderItems
	return theCount
end countWatchfolder

I think you probably want to use an On Idle handler, not On Launched
Then you can do the func every couple seconds/minutes
and the app isn’t taking up your whole CPU with the launched handler that will never really finish

Thank You. I can’t believe it was that easy. However, you raised some alarm bells and I started looking into CPU usage after putting it into the on idle handler: still over 20% cpu on a dual core mac. Is this normal for a progress bar? Is there another way that is less cpu intensive?

SuperMacguy’s approach is better but if you attach the progress window to your main window they will both stay in the foreground and they can’t be “separated”.

like

update window "Monitor" attached to window "Main"