Preventing Script timeout: exhausted allowed execution time on nested For Loops

I have the following code, and it sometimes results in an Script timeout: exhausted allowed execution time error… sometimes, not sure why only sometimes, but it happens and often.

function Module.LoopMatrix(day)
	for firstKey = 1, 50, 1 do 
		for secondKey = 2, 51, 1 do 
			if secondKey > firstKey then

				for thirdKey = 3, 52, 1 do 
					if thirdKey > secondKey then

						local secondKeyStr = tostring(secondKey)
						local thirdKeyStr = tostring(thirdKey)
						local dayTriadCount = Data["Days"][day]["Combos"]["Triads"]["Matrix"][firstKey][secondKeyStr][thirdKeyStr]

						if dayTriadCount > 0 then
							Data["Days"][day]["Combos"]["Triads"]["Matrix"][firstKey][secondKeyStr][thirdKeyStr] = dayTriadCount - 1



function Module.RunMatrixForEachDay()
	for day = 1, 365, 1 do

The error happens at one of the For Loops, usually the third or fourth one.
I thought execution timeout / exhaustion errors were only possible on While and Repeat loops. I do not use While loops, but I do use Repeat loops here and there, and to prevent exhaustion errors I use RunService.Heartbeat:Wait() with the Repeat loops, but that doesn’t seem to work with the For Loops. If I try to use RunService.Heartbeat:Wait() the thread simply stops.

I am wondering if maybe I can use task.spawn() and task.wait() somehow to prevent exhaustion error with the nested for loops. I have never used those methods, so I am not sure if that is the right approach, also because I do not fully understand why the error happens in the first place.

Any advice / tips / suggestions on how to tackle this issue would be appreciated.

Extra Note: The code is literally just doing mathematical calculations, I am not doing anything with any parts, objects, instances, GUIs, or anything anywhere in the game with those particular functions / for loops. So the exhaustion is not related to any physics/objects/connections etc.