'From Cuis 1.0 of 28 November 2009 [latest update: #337] on 5 January 2010 at 3:27:02 pm'!

!WorldState methodsFor: 'update cycle' stamp: 'jmv 1/5/2010 15:09'!
interCyclePause: milliSecs
	"delay enough that the previous cycle plus the amount of delay will equal milliSecs.  If the cycle is already expensive, then no delay occurs.  However, if the system is idly waiting for interaction from the user, the method will delay for a proportionally long time and cause the overall CPU usage of Squeak to be low."

	| wait |
	waitDelay ifNil: [ waitDelay _ Delay forMilliseconds: 50 ].
	wait _ Preferences serverMode
		ifFalse: [
			(lastCycleTime notNil and: [CanSurrenderToOS ~~ false]) 
				ifTrue: [ lastCycleTime + milliSecs - Time millisecondClockValue ]
				ifFalse: [  0 ] ]
		ifTrue: [ 50 ].
	(wait > 0 and: [ wait <= milliSecs ] )
		ifTrue: [
			waitDelay beingWaitedOn
				ifFalse: [ waitDelay setDelay: wait; wait ]
				ifTrue: [
					"If we are called from a different process than that of the main UI, we might be called in the main
					interCyclePause. In such case, use a new Delay to avoid 'This Delay has already been scheduled' errors"
					(Delay forMilliseconds: wait) wait]].

	lastCycleTime _  Time millisecondClockValue.
	CanSurrenderToOS _ true! !

