There is an error in the script, from Autosave

I have a script where they mark the seconds (LeaderStats), but I want this script to be saved for each of the players

Script “TimePlayed” - “ServerScriptService”:
Screenshot_41

And I thought about doing the self-storage this way, but it didn’t work.I have a problem with the script and I don’t know what to do?

Script AutoSave:

local datastore = game:GetService("DataStoreService")
local DS1 = datastore:GetDataStore("TimePlayedSaveSystem")

--function Player Added
game.Players.PlayerAdded:connect(function(plr)

	
-- LEADERBOARD ---
 local folder = Instance.new("Folder", plr)
 folder.Name = "leaderstats"
 local TimePlayed = Instance.new("IntValue", folder)
 TimePlayed.Name = "TimePlayed"

-- Code of Save
 
 TimePlayed.Value = DS1:GetAsync(plr.UserId) 
 DS1:SetAsync(plr.UserId, TimePlayed.Value)
 
  TimePlayed.Changed:connect(function()
  DS1:GetAsync(plr.UserId, TimePlayed.Value)
 end)
end)

Please do not send images of code; instead, copy and paste your code into code blocks.

You do not have to create the leaderstats in both scripts.

Why are you doing DataStore:SetAsync() right after DataStore:GetAsync()?

You should not be saving the data every time the value is changed because data stores have a cooldown. There is a 6-second cooldown between write requests to the same key.

It doesn’t work either

local datastore = game:GetService("DataStoreService")
local DS1 = datastore:GetDataStore("TimePlayedSaveSystem")

--function Player Added
game.Players.PlayerAdded:connect(function(plr)

	
-- LEADERBOARD ---
 local folder = Instance.new("Folder", plr)
 folder.Name = "leaderstats"
 local TimePlayed = Instance.new("IntValue", folder)
 TimePlayed.Name = "TimePlayed"

-- Code of Save
 
 TimePlayed.Value = DS1:GetAsync(plr.UserId) 
 DS1:SetAsync(plr.UserId, TimePlayed.Value)
 
  TimePlayed.Changed:connect(function()
  DS1:GetAsync(plr.UserId, TimePlayed.Value)
 end)
end)

Why are you SetAsync right after you got the data. It should be like:

local data
local success, failure = pcall(function()
    data = dataStore:GetAsync(plr.UserId)
end)

if data then
    TimePlayed.Value = data.TimePlayed or 0
else error(“Failed to get data store. Code: “.. failure)

Then after that function, just make it so that whenever a second has passed for them, add 1 to their value. I recommend spawning a thread because if not, the increment would have to rely on the server which would increase the value for everyone in the server at the same time.

save the data when the player leaves instead of when the value changes because if you call the datastore too much it cancels your save requests

Calling the datastore so much in a short time is very bad. You don’t need to store the value every second.