Timeout
Server & Client Supported
ภาพรวม
ฟังก์ชันสำหรับจัดการการทำงานแบบหน่วงเวลา
ที่อยู่ไฟล์
source/modules/core/timeout.lua
ฟังก์ชัน
SetTimeout
ตั้งเวลาให้ฟังก์ชันทำงานหลังจากเวลาที่กำหนด
พารามิเตอร์
ประเภท
คำอธิบาย
msec
number
เวลาที่ต้องการหน่วง (มิลลิวินาที)
cb
function
ฟังก์ชันที่จะทำงานหลังหน่วงเวลา
ค่าที่ส่งกลับ:
number
- ID ของ timeout (ใช้สำหรับยกเลิก)nil
- ถ้าเกิดข้อผิดพลาด
-- ตัวอย่างการใช้งานพื้นฐาน
AFUCore.SetTimeout(5000, function()
print('ทำงานหลังจาก 5 วินาที')
end)
-- ตัวอย่างการเก็บ ID เพื่อยกเลิก
local timeoutId = AFUCore.SetTimeout(10000, function()
print('ข้อความนี้จะไม่แสดงถ้าถูกยกเลิก')
end)
-- ตัวอย่างการใช้กับการแจ้งเตือน
AFUCore.SetTimeout(3000, function()
AFUCore.ShowNotification('แจ้งเตือนหลัง 3 วินาที')
end)
-- ตัวอย่างการใช้แบบต่อเนื่อง
local function loop()
print('ทำงานทุก 1 วินาที')
AFUCore.SetTimeout(1000, loop)
end
loop()
ClearTimeout
ยกเลิกการทำงานของ timeout ที่ตั้งไว้
พารามิเตอร์
ประเภท
คำอธิบาย
tid
number
ID ของ timeout ที่ต้องการยกเลิก
-- ตัวอย่างการยกเลิก timeout
local tid = AFUCore.SetTimeout(5000, function()
print('ข้อความนี้จะไม่แสดง')
end)
-- ยกเลิก timeout ทันที
AFUCore.ClearTimeout(tid)
-- ตัวอย่างการยกเลิกแบบมีเงื่อนไข
local notificationId = AFUCore.SetTimeout(10000, function()
AFUCore.ShowNotification('แจ้งเตือนสำคัญ')
end)
-- ยกเลิกถ้าผู้เล่นออกจากพื้นที่
AddEventHandler('playerLeftArea', function()
AFUCore.ClearTimeout(notificationId)
end)
การใช้งานขั้นสูง
การทำงานเป็นลำดับ
-- ทำงานเป็นลำดับด้วย timeout
AFUCore.SetTimeout(1000, function()
print('ขั้นตอนที่ 1')
AFUCore.SetTimeout(1000, function()
print('ขั้นตอนที่ 2')
AFUCore.SetTimeout(1000, function()
print('ขั้นตอนที่ 3')
end)
end)
end)
การทำ Animation ด้วย Timeout
local function fadeOut(opacity)
if opacity > 0 then
SetEntityAlpha(entity, opacity)
AFUCore.SetTimeout(50, function()
fadeOut(opacity - 0.1)
end)
end
end
fadeOut(1.0) -- เริ่ม fade out
หมายเหตุ
ใช้ระบบ timeout ด้วยความระมัดระวังเพื่อไม่ให้กระทบ performance
ควรยกเลิก timeout ที่ไม่จำเป็นเสมอ
หลีกเลี่ยงการใช้ timeout ซ้อนกันหลายชั้นเกินไป