How to make saving stopwatch

For example if I make a cooldown and it starts at 5:00 and starts counting and it stays at 4;3 cause the player leaves the game how do I save it there

2 Likes

Hust save it in a datastore and load it later.

2 Likes
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local Time = DataStoreService:GetDataStore("Time")
local TotalTime = ""

Players.PlayerRemoving:Connect(function(Player)
	Time:SetAsync(Player.UserId, TotalTime)
end)

Players.PlayerAdded:Connect(function(Player)
	TotalTime = ""

	local Minutes = 3
	local Async = Time:GetAsync(Player.UserId)

	if Async ~= nil then
		TotalTime = Async
		
		print("Player rejoined with the time of " .. TotalTime)

		local Time = string.split(TotalTime, ":")

		local Minute = Time[1]
		local Second = Time[2]

		repeat 
			repeat
				Second -= 1

				if Second <= 9 then
					TotalTime = Minute .. ":0" .. Second
				else
					TotalTime = Minute .. ":" .. Second
				end
				
				print(TotalTime)
				
				task.wait(1)
			until Second <= 1

			Second = 59
			Minute -=1

			task.wait(1)
		until Minute <= -1
	else
		for Minute=Minutes, -1, -1 do
			for Second=59, 1, -1 do
				task.wait(1)

				if Second <= 9 then
					TotalTime = Minute .. ":0" .. Second
				else
					TotalTime = Minute .. ":" .. Second
				end
				
				print(TotalTime)
			end
		end
	end
end)

my brain fried

2 Likes

With questions like these, you shouldnt just fat out give the answer, its clear the person didnt even try or doesnt know what data store is and is gonna just copy and paste what you gave him an move on

He does now. :wink: The very best way to learn anything is by example.

local Game = game
local Players = Game:GetService("Players")
local DataStoreService = Game:GetService("DataStoreService")
local TimeStore = DataStoreService:GetDataStore("TimeStore")

local function OnPlayerAdded(Player)
	Player:SetAttribute("Time", os.time()) --Join time.
	local Success, Result = pcall(function() return TimeStore:GetAsync(Player.UserId) end)
	if not Success then warn(Result) end
	Player:SetAttribute("Timer", Result or 300) --Saved value or 300 seconds.
	task.wait(Result or 300) --Wait for timer.
	--Timer has finished.
end

local function OnPlayerRemoving(Player)
	local Time = math.max(0, (Player:GetAttribute("Timer") - (os.time() - Player:GetAttribute("Time")))) --Get largest value of either 0 or the player's timer subtracted by the length of time they played for.
	local Success, Result = pcall(function() return TimeStore:UpdateAsync(Player.UserId, function(_) return Time end) end)
	if not Success then warn(Result) end
end

local function OnGameClose()
	for _, Player in ipairs(Players:GetPlayers()) do
		OnPlayerRemoving(Player)
	end
end

Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)
Game:BindToClose(OnGameClose)
1 Like

I actually know what datastores are it’s just that I didn’t know how to save the values to them