While true do loop speeds up

Maybe the while wait(3) do part is messing things up.

wait() will yield as close as possible for the given amount of seconds on top of waiting for an open slot in the scheduler so it can take up to more than 3 seconds in this case but it doesn’t have the issue of resuming the thread before the given time, so there must be some other flaw in the implementation.

while true do
     local t = os.clock() 
     wait(5)
     print(os.clock() - t)
end
-- tick will be deprecated in the future by the way

Edit:

You could use a Heartbeat wait for more precise yielding,

@Canopius

@ zeuxcg

tick() sounds perfect - it has a high resolution (usually around 1 microsecond), and a well-defined baseline - it counts since UNIX epoch! Or, well, it actually doesn’t. On Windows, it returns you a variant of the UNIX timestamp in local time zone. In addition, it can be off by 1 second from the actual, real UNIX timestamp, and might have other idiosyncrasies on non-Windows platforms. We’re going to deprecate this in the future.
[/quote]

2 Likes

I would not recommend to use a while wait loop, mainly because they are not guaranteed to fire when you want them to, more information can be found here.

You can use heartbeat instead and check to see if 3 seconds have passed since the last update.

local RunService = game:GetService("RunService")
local NextStep = tick()


RunService.Heartbeat:Connect(function()
	if tick() >= NextStep then
		NextStep = NextStep + 3
		-- Code
	end
end)

And @XxELECTROFUSIONxX, where did you see that tick() is going to be deprecated?

1 Like

The seconds value does not even go up now:

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local checkpoints = workspace.Checkpoints
local ga = false
local NextStep = tick()
Players.PlayerAdded:Connect(function(Player)
	local PlayerDataStore = DataStoreService:GetDataStore("PlayerStore", Player.UserId)
	warn("Initializing leaderstats...")
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	stats.Parent = Player
	local wipeouts = Instance.new("IntValue")
	wipeouts.Name = "Deaths"
	wipeouts.Parent = stats
	local second = Instance.new("IntValue")
	second.Name = "Seconds"
	second.Parent = stats
	 local stage = Instance.new("IntValue")
    stage.Name = "Stage"
	stage.Parent = stats
	print("Completed.")
	
	warn("Initializing leaderstats values...")
	local success = PlayerDataStore:GetAsync("success")
	local PlayerData = PlayerDataStore:GetAsync("PlayerData")
	if success == nil or false then
		print("Player is currently nil")
		PlayerDataStore:SetAsync("success", true)
		PlayerDataStore:SetAsync("PlayerData", HttpService:JSONEncode({deaths = 0, sec = 0, stages = 0}))
		Player:Kick("Rejoin, you have no data")
	elseif success == true then
		local decoded = HttpService:JSONDecode(PlayerData)
		--for k,v in pairs(decoded) do
		--print(k, v, type(v))
		--end
		Player.leaderstats.Deaths.Value = decoded.deaths
		Player.leaderstats.Seconds.Value = decoded.sec
		Player.leaderstats.Stage.Value = decoded.stages
		print(success)
		print("Completed.")
		warn("Continuing with normal RunTime")
		Player.CharacterAdded:connect(function(Character)
			local humpart = Character.HumanoidRootPart
			RunService.Stepped:wait()
        humpart.CFrame = checkpoints[stage.Value].CFrame+ Vector3.new(0,math.rad(3.5),0)
			local d = true
			Character:WaitForChild("Humanoid").Died:Connect(function()
			RunService.Stepped:wait()
        humpart.CFrame = checkpoints[stage.Value].CFrame + Vector3.new(0,math.rad(3.5),0)
				if d then
					Player.leaderstats.Deaths.Value += 1
				end
			end)

			RunService.Heartbeat:Connect(function()
	if NextStep >= tick() then
		NextStep = NextStep + 1
		Player.leaderstats.Seconds.Value +=1
	end
end)
		
		end)
	end
end)

Players.PlayerRemoving:Connect(function(Player)
	ga = true
	local PlayerDataStore = DataStoreService:GetDataStore("PlayerStore", Player.UserId)
	warn(string.format("%s IN QUEUE...", Player.Name:upper()))
	local death = Player.leaderstats.Deaths.Value
	local secs = Player.leaderstats.Seconds.Value
	local stagess = Player.leaderstats.Stage.Value
	local data = {deaths = death,sec = secs, stages =stagess }
	local encoded = HttpService:JSONEncode(data)
	PlayerDataStore:SetAsync("PlayerData", encoded)
	print("Done")
end)

It is more inefficient but you could try if all else fails using
while true do
Wait(1) —or whatever it is

I hope this helps.

1 Like

That is what I used to do but as the player played longer, it started speeding up.

Hi there would you have a game link so we can observe this?

Thanks.

It is just out of interest.

My mistake, the NextStep and tick() should be the other way around:
if NextStep >= tick() thenif tick() >= NextStep then

1 Like

Did I put the function in the correct place in my code?

Yes, that should work although you need to remember to disconnect when the player leaves.

It is also not that efficient having so many listeners, while this is optional it would improve performance, is to have the Heartbeat function separate and loop through all of the players inside of it constantly.

1 Like

How can I do that? A code sample will be helpful. This is what it is like now.

I observed the place-file, and it’s not “speeding up” any sort of loop, just increase the amount of seconds you pass to the wait function if you feel it’s too quick.

Yep I was being stupid :sweat_smile:

1 Like

I do not understand what you mean. I want it to save which it does so the leaderboard showing how long the were playing for works (global leaderboard).

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

RunService.Heartbeat:Connect(function()
	if not (tick() >= NextStep) then return false end
	NextStep = NextStep + 3
	local Plrs = Players:GetChildren()
	for index = 1, #Plrs do
		-- Code here
	end
end)
1 Like

So the whole time amount of seconds?

I do not understand the way you are trying to say. Try re phrasing

the part where is say nextstep + 3, does that mean every three seconds. Doesn’t matter, I think it does, i changed it to 1 and now it goes up every second.

The issue is that you engage a while loop each time a player spawns but only break them when the player leaves and not when a character is removed, leading to multiple while loops running for each player after they respawn. You could set ga to true with the CharacterRemoving event.

1 Like