A trick for a “custom” delay is using the
RunService.Heartbeat event. I use this if I want a short delay and if I don’t want to clog up my coroutines. It’s just another method that I like using with other methods such as coroutines.
I like using this in a module that I can require from the client and server side so it isn’t repeated in multiple scripts.
function module:Delay(waitTime, andThen)
local timeCount = 0;
local allow = true;
connection = RunService.Heartbeat:Connect(function(delta)
timeCount += delta
if timeCount >= waitTime and allow then
allow = false;
Benchmarking under heavy script load and performance:
Delaying for 5 seconds:
Local Script: 4.9397112999999
IMPORTANT: Please remember to not just rely on this one method, and use a couple methods combined to get the best optimization possible. Use
coroutine for important back-end code, and something like this for front-end code such as UI, Visual Effects, User Input, etc.
This method is also only efficient for very big projects which is what I tend to create. If you’re planning on making a small project that doesn’t have many events, delays, waits, coroutines, etc. then just keep using