How come this code works as expected (seconds = 1)?
local function wait( seconds )
C_Timer.After( seconds, function() print("Hello World!") end )
C_Timer.After( seconds + 1, function() print("Hello World!") end )
C_Timer.After( seconds + 2, function() print("Hello World!") end )
C_Timer.After( seconds + 3, function() print("Hello World!") end )
end
In other words, this implementation prints a line of text, “Hello World”, as intended - 4 lines of text with a 1 second delay between each line. By contrast, this implementation does not?
local seconds = 1
for i = 1, 4 do
seconds = seconds + (i - 1)
wait( seconds )
end
In this case, the 16 lines of text are printed where the 1 second delay occurs between every 4 lines.
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
local Counter = 0
local Ticker = C_Timer.NewTicker(0.5, function()
Counter = Counter + 1
print("Counting", Counter)
end, 10)
You can cancel the ticker at any time with
Ticker:Cancel()
This code:
local function wait( seconds )
C_Timer.After( seconds, function() print("Hello World!") end )
C_Timer.After( seconds + 1, function() print("Hello World!") end )
C_Timer.After( seconds + 2, function() print("Hello World!") end )
C_Timer.After( seconds + 3, function() print("Hello World!") end )
end
local seconds = 1
for i = 1, 4 do
seconds = seconds + (i - 1)
wait( seconds )
end
Is producing the 4 prints with a one second gap after every 4th?
It should be printing:
no lines when started
one line at the first second (loop 1)
two lines at the second second (loops 1 and 2)
two lines at the third second (loops 1 and 2)
three lines at the fourth second (loops 1, 2 and 3)
two lines at the fifth second (loops 2 and 3)
one line at the sixth second (loop 3)
two lines at the seventh second (loops 3 and 4)
one line at the eighth second (loop 4)
one line at the ninth second (loop 4)
one line at the tenth second (loop 4)
You probably already know this, but to be clear, the client doesn’t pause while waiting for the C_Timer.After() to do its thing. It will queue up something to happen after X seconds and move on to run the next line of code. Your loop is queueing up 4 things to print over a span of time and the execution path will have finished before it does a single tick of a timer. Put a print outside of a delay at the end of your code to see.
Your loop is starting a queued sets of prints that begin at 1, 2, 3 and 4 seconds after the code has executed and staggers after that.
1 Like