Help to prevent lag, fix forced scripts

Hey everyone, so Im trying to make my game stop lagging, because at random times it begins lagging, Heres the music script that seems to cause some of it:

  --||Locals||--

 local Player = game.Players.LocalPlayer
local MS = game:GetService("MarketplaceService")
local Song = script.Parent:WaitForChild("Sound")

 local Songs = {
	4277136473,
	279206904,
	639750143,
	279207008,
	225000651,
	165065112,
	1836842889,
	1838058421,
	1837324424,
	1845554017,
	1837767023,	
}
 -----------------
 --||Functions||--
 -----------------
function NewSong()
	local RndmInt = math.random(1,#Songs)
	local SongId = Songs[RndmInt]
	if Song.SoundId ~= "rbxassetid://"..SongId then
		Song.SoundId = "rbxassetid://"..SongId
		if script.Parent.Parent:WaitForChild("Settings"):WaitForChild("Sounds").Value == true then
			Song:Play()
		end
		local SongInfo = MS:GetProductInfo(SongId)
		if SongInfo.Name then
			script.Parent:WaitForChild("SongName").Text = SongInfo.Name
		else
			script.Parent:WaitForChild("SongName").Text = "[ Unknown ]"
		end
		--
		if Song.TimeLength ~= nil and Song.TimeLength > 0 then
			wait(Song.TimeLength)
		end
		--
		NewSong()
	else
		NewSong()
	end
end
----------------
--||Start Up||--
 ----------------
 NewSong()

(It is a local script, and is located in StorageGUI with the music GUI).

Anyone have any tips to stop the lag?

Since you are using recursion(having a function call itself), the lag probably occurs because the function calls itself multiple times, and then those new functions call themself multiple times etc. causing the lag to just multiply. Could you format your code better so we can see where the recursion messes up. To format your code do three of these ` (the key below the esc key).

--```
--code here
--```

There, I fixed it! Is that good?

1 Like

As @XdJackyboiiXd21 mentioned, having a function call it self is not ideal. I would make it so the function doesn’t call itself and instead use the Sound.Ended event. So when a song’s playback finishes the function to play a new song is triggered.

I’ve also noticed that some of the songs in your list have been removed so I would go through and check which ones are still useable. A way to prevent this in case the assets are removed later is to wrap Song.SoundId = "rbxassetid://"..SongId in a pcall so if it errors the script won’t stop.