«simple function throttling ( time gate, time limiter, whatever you want to call it )» by hems

on 24 Dec'13 09:38 in simplefunctionthrottlingtimegatelimiter

A friend of mine asked me how to limit a function to happen at maximun rate of 1 time every N seconds..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
(

  ~needed_interval = 20;

  ~funk = {

	// if last time isn't defined, create it with 1000 seconds ago time
	if( ~last_time.isNil ) {
		~last_time = Date.getDate.bootSeconds;
		~last_time = ~last_time - 1000;
	};

	// if needed interval has passed, execute the funkie
	if( ( Date.getDate.bootSeconds - ~last_time ) > ~needed_interval ) {

		// safe last execution time, so next calls will have to wait the needed interval
		~last_time = Date.getDate.bootSeconds;

		( "SOMETHING HAPPENS HERE AT MAXIMUN RATE OF 1 TIME EACH" + ~needed_interval + " SECONDS " );

	} {
		( "YOU STILL HAVE TO WAIT" );
	}
  };
)

~funk.value()
raw 651 chars (focus & ctrl+a+c to copy)
reception
comments