Module Script
local module = {} function module:StartTimer(Time,Playback) local timerThread = coroutine.wrap(function() for i = Time, 0, -Playback do local minutes = math.floor(i/60) local seconds = math.floor(i%60) print(string.format("Time: %i:%.2i", minutes, seconds)) wait(1) end end) timerThread() end function module:StopTimer() end return module
How would I go about stopping this timer with the "StopTimer()" function after waiting for 5 seconds (as shown below).
Server Script
local sS = game:GetService("ServerStorage") local Timer = require(sS:WaitForChild("ModuleScript")) Timer:StartTimer(100,1) wait(5) Timer:StopTimer()
You could try stopping a thread with a variable outside the function and using break
to exit the loop like:
local module = {} local stop_flag = false function module:StartTimer(Time,Playback) local timerThread = coroutine.wrap(function() for i = Time, 0, -Playback do if(stop_flag) then break end local minutes = math.floor(i/60) local seconds = math.floor(i%60) print(string.format("Time: %i:%.2i", minutes, seconds)) wait(1) end end) timerThread() end function module:StopTimer() stop_flag = true end return module
If there you would call this thread multiple times then I suggest you pass each of them a BoolValue that would be instantiated somewhere in the workspace and getting rid of it at the end of the thread
Here is a sample of where you create a boolean flag in case you want to keep calling the function without it affecting each other, do note that you have to return the flag so you can pass it to the stop function:
local module = {} function module:StartTimer(Time,Playback) local stop_flag = Instance.new("BoolValue", workspace) local timerThread = coroutine.wrap(function(stop_flag) for i = Time, 0, -Playback do if(stop_flag.Value) then break end local minutes = math.floor(i/60) local seconds = math.floor(i%60) print(string.format("Time: %i:%.2i", minutes, seconds)) wait(1) end end) timerThread(stop_flag) return stop_flag end function module:StopTimer(stop_flag) stop_flag.Value = true end return module
now to call the functions:
local sS = game:GetService("ServerStorage") local Timer = require(sS:WaitForChild("ModuleScript")) local flag1 = Timer:StartTimer(100,1) local flag2 = Timer:StartTimer(100,1) wait(5) Timer:StopTimer(flag1) Timer:StopTimer(flag2)