Issues with cancelling threads

Hey everyone! Recently, i’ve been working on fixing memory leaks in my game, and what i’m doing first is trying to cancel / stop threads after i’m done using them (I have WAY too many task.spawn()s all around my code). I have attempted to do this by using task.cancel(), but this doesn’t seem to work and i receive the error cannot cancel thread each time. I know this might be because i’m trying to cancel the thread while it’s running, but i don’t know how to wait for it to be completed to cancel it. Can anyone help me in how to implement this, or if it’s even necessary?

Code:

local newthread

newthread = task.spawn(function()
	local friends = Players:GetFriendsAsync(localPlayer.UserId)
	local ids = table.create(200) -- max friends limit
	local count = 1

	while task.wait() do
		for _, item in ipairs(friends:GetCurrentPage()) do
			ids[count] = item.Id
			count += 1
		end

		if friends.IsFinished then
			break
		end

		friends:AdvanceToNextPageAsync()
	end

	local randomFriendId = ids[math.random(1,count)] -- nil if no pages are available :(
	if randomFriendId then
		friendsText = "This one's to "..Players:GetNameFromUserIdAsync(randomFriendId).."!"
		
		print(friendsText)
		
		task.cancel(newthread)
	end
end)

Any help is appreciated!