How do I make a countdown before giving afk status?

So, I’m making a program that detects AFK status via UserInputService with # of seconds before giving them the AFK status. but when the player returns, the timer should be canceled so it won’t give the player the AFK status.

My current script as of now…

local DURATION = 10 -- Wait # of seconds before giving the AFK status
local AFK_Status = false

UserInputService.WindowFocused:Connect(function()
	AFK_Status = false
	AFKEvent:FireServer(AFK_Status)
end)

UserInputService.WindowFocusReleased:Connect(function()
	AFK_Status = true
	spawn(function()
		-- Don't know what to put next. But im not sure either if I should use spawn
	end)
end)

Edit 1: It seems using the spawn() will overlap the current release event.

1 Like

It seems I can just do this. and it works perfectly well.

local DURATION = 10 -- Wait # of seconds before giving the afk status
local AFK_Status = false

UserInputService.WindowFocused:Connect(function()
	print("Focused")
	AFK_Status = false
	AFKEvent:FireServer(AFK_Status)
end)

UserInputService.WindowFocusReleased:Connect(function()
	print("Release")
	AFK_Status = true
	
	local Inc = DURATION
	while AFK_Status == true do
		if Inc == 0 then
			AFKEvent:FireServer(true)
			break
		else
			Inc = Inc - 1
		end
		
		print("afk in:", Inc)
		task.wait(1)
	end
end)

If any improvements you can recommend, please reply. I appreciate if you do that.