How do I not use "polling"?

So I have this system where every “tick” which should be like every half second, that a certain action happens (value added) which for I naturally use task.wait(), and I hear everyone saying how its code smell and not a good coding practice, does anyone know a good alternative to this is:

while true do
task.wait(0.5)
-- do action ex: give salary
end

Summarized: Basically what I’m looking for is ideas on how to do something every 0.5 second without polling

task.spawn(function()
	while task.wait(5) do
		--do action
	end
end)

This creates an entirely new thread to handle the code (allowing the main thread to continue executing code within the script), and you can replace true with the task.wait() call.

Alternatively you can use RunService.Stepped or RunService.HeartBleed but those typically used for loops which should execute every frame or every other frame not every 30 frames as in your example.

Do you mean something like this resource?

1 Like

It depends what you’re trying to do. Some things don’t need to be polled, but some things do. I don’t think it’s bad practice as long as you’re doing it for the right things.

Something like giving money every X seconds I’d say is fine - you might want to compare the time since the last money giving because wait() and task.wait() technically can be much longer than you put, but it generally isn’t an issue.

2 Likes

It’s bad to poll things that don’t need to be polled. Ex: listening to mouse changes every frame to detect if it moved or not, when you could instead bind an event to UserInputService.InputBegan.

As for your example, “give salary”, you could instead bind the salary event to when the player does something - for instance when they finish baking a pizza. But other than that, polling isn’t always bad - it just depends on the context.

3 Likes

A lot of things are time based like in real life where you get a monthly salary for example which I guess have to use polling for

Didn’t really answer the question but the resources are good

1 Like