Wait

From Warcraft Wiki
Jump to navigation Jump to search
This is a user-defined function that you can copy and paste into your addon.

Call this function to wait a specified amount of time before running another function with the given parameters. This function is useful when you rely on system messages to trigger your code as (especially with Guild related system messages) the system message is dispatched by the server sometimes before the results have been updated. Waiting to perform the next step of your code becomes easy with this function.

<PREFIX>_wait(delay, func [, param [,param [,...]]])

Function Parameters

Arguments

delay
Number - the amount of time to wait (in seconds) before the provided function is triggered
func
Function - The function to run once the wait delay is over.
param
any - A list of any additional parameters (of any assorted type) to pass to the provided function when it is triggered.

Returns

success
Boolean - true if it succeded in adding the wait to the wait table, If the first parameter is not a number, or the seconds parameter is not a function, any call to wait will automatically fail with a result of false.

NOTE: if the UIParent frame is being hidden, this wait will not work. It will never reach the end of the delay.

Example

<PREFIX>_wait(2.5,<PREFIX>_printMSG,"Hello");

Result

returns true after the initial call
after a 2.5 seconds delay, the string "Hello" will be displayed in the default chat frame.

Code

local waitTable = {}
local waitFrame = nil

function <PREFIX>_wait(delay, func, ...)
  if(type(delay) ~= "number" or type(func) ~= "function") then
    return false
  end
  if not waitFrame then
    waitFrame = CreateFrame("Frame", nil, UIParent)
    waitFrame:SetScript("OnUpdate", function (self, elapse)
      for i = 1, #waitTable do
        local waitRecord = tremove(waitTable, i)
        local d = tremove(waitRecord, 1)
        local f = tremove(waitRecord, 1)
        local p = tremove(waitRecord, 1)
        if d > elapse then
          tinsert(waitTable, i, {d - elapse, f, p})
          i = i + 1
        else
          count = count - 1
          f(unpack(p))
        end
      end
    end)
  end
  tinsert(waitTable, {delay, func, {...}})
  return true
end