Stopping a module function when it is called again

I’m creating a text chat UI for a tutorial, this is the module function I have

function module.CharacterChat(text)
	for i = 1, string.len(text) do 
        task.wait(0.025)
		textLabel.Text = string.sub(text, 1, i)
	end
end

And when I call it it produces the correct result. However, sometimes when you skip a step the function is still running when I call it again causing glitchy text switching back and forth because it is being ran twice. How can I call module.CharacterChat() and have the other function instance stop from when I called it before?

You should be storing if its currently running for the desired instance. Example:

local actions = {}
local Iteration = 1
function module.CharacterChat(text)
	Iteration +=1
	local UniqueID = Iteration
	actions[text] = Iteration

	
	for i = 1, string.len(text) do 
		task.wait(0.025)
		if actions[text] ~= UniqueID then
			break
		end
		textLabel.Text = string.sub(text, 1, i)
	end
end

This code will make it impossible for the same instance to run above >1 at the same time

1 Like

Ah I see. However, the text parameter being passed in is different every time as they are different phrases being displayed.

Ah my bad i didnt realise that your textlabel is predefined in the module. I highly recommend that you do this instead: function module.CharacterChat(DESIREDTEXTLABEL,text)
This way the module is more “use-able” as it will apply to any textlabel you provide in the parameter

Ah I meant the ‘text’ parameter is different every time but I re read the code and that wasn’t the issue I misguided sorry. Here is a video of the code being ran

As you can see for a split second the text getting glitchy and not resetting like intended still. I’m examining the code and I still don’t know why cause I believe you are right.

The change to my code would be that instead of storing the text you would store the textlabel in actions. This is my fault as I wasn’t paying attention the parameters. e.g instead of actions[text] it would be actions[textlabel]

Ah, I see what you mean now. Thank you!