# Timer.pm --- implements a countdown timer 

package Timer;

# Create a Timer class instance (instantiation)
sub new {
	my $class = ref($_[0]) || $_[0];
	my $this = {};
	$this->{'interval'} = $_[1];	# set interval in seconds
	bless $this, $class;
	return $this;
}

# You attach a listener so that when some events occur,
# the "callback" listener subroutine would be invoked.
# This is a good place for caller to perform some actions
# in respond to the event.

# If you have programmed Java Swing before, this concept
# and terminology should be familiar to you.
sub addListener {
	my $this = $_[0];
	# push (sub reference, object reference) into listener list
	push @{$this->{'listeners'}}, [$_[1], $_[2]];
}

# Start countdown timer
sub start {
	my $this = $_[0];
	my $starttime = time;
	while (time - $starttime <= $this->{'interval'}) {
		# no-op
	}
	# Timer stops. Notify listeners.
	foreach (@{$this->{'listeners'}}) {
		# Invoke each listener
		my $subref = ${$_}[0];
		(${$_}[1])->$subref();
	}
}

1;
