Delay between operations in Lua script

I want to do one operation after another but with some delay.
I use this code in Lua script

local delay = 500  -- milliseconds

while true do
    local currentTime = millis()
    if currentTime - lastActionTime >= delay then
        break
    end
    -- Insert other necessary operations here if needed
end

but has an error exceeded time.
Can somebody help me to avoid this error? Thank you.

You need to use a scheduled callback. Infinite loops and local delay logic will always time out due to the way ArduPilot’s Lua engine is run at scheduled intervals.

local delay = 500  -- milliseconds

local function myScheduledFunction()
    -- Insert other necessary operations here if needed
end

return myScheduledFunction, delay