Timer Troubles - Variable alternates between 1 and 0 when fully counted down

Hey all,

Short time lurker, first time caller here.

Below I have code for a timer that counts down every second from 3 to 0. It counts down to 0 as expected, but then rapidly bounces between 1 and 0 for what I assume is every frame, maybe for a couple seconds before returning to 0.

Using 'sleeptimer--' resulted in it being lowered every frame, so I decided to just hard code it.

The only thing that the player does with the 'sleeptimer' variable currently is show it in a label.

In 'game':

on load do

	awake = "false"
	sleeptimer=3

end

on loop do	

        if awake =="false" then
	       call "sleep"
        end

end

on sleep do
		
	wait 1 then
		tell event.player to
			sleeptimer = 2
		end
	end
		
	wait 2 then
		tell event.player to
			sleeptimer = 1
		end
	end
		
	wait 3 then
		tell event.player to
			sleeptimer = 0
		end
		awake="true"
         end
		
end

Strangely, adding an additional second to the last wait statement fixes the issue. I can work with this if I have to, but I want to know what I'm doing wrong.

	wait 1 then
		tell event.player to
			sleeptimer = 2
		end
	end
	
	wait 2 then
		tell event.player to
			sleeptimer = 1
		end
	end
	
	wait 4 then
		tell event.player to
			sleeptimer = 0
		end
		awake = "true"
	end

The end goal is to have a timer that counts down from 3, then waits at 0 for some seconds while something happens before restarting back at 3, which, with the exception of this issue I have figured out. I just stripped it down to the simplest version for troubleshooting.

Anyone know what I'm doing wrong? Any help is greatly appreciated! :slight_smile:

You are making a few mistakes here, you can create a loop that ticks down the variable by one every second, and stops when it detects the variable is at zero, instead of the complicated method you are using, the code I came up with is:

on enter do
if slept==0 then
slept = 1
awake = 0
sleep_timer = 3
call “sleep”
end
end

on sleep do
if sleep_timer!=0
wait 1 then
sleep_timer -= 1
call “sleep”
end
if sleep_timer==0 then
awake = 1
end

To check awake, know it will be true if one, and false if two.

1 Like

This is much simpler and fixes the bug, thank you! I'm used to the syntax of Python and I tend to overcomplicate when trying to work with a new syntax.. haha.

I was able to modify it a bit to suit what I needed.