@rbxts/jsnatives
setTimeout
Schedules a function to be executed after a specified delay.
Signature
function setTimeout(cb: (sym: symbol) => void, ms = 0): symbol
Description
The setTimeout
function schedules the execution of a callback function after a specified delay in milliseconds. It returns a symbol that can be used to cancel the timeout using clearTimeout
.
Internally, it uses Roblox's task.delay
function to implement the timeout behavior.
Parameters
cb
: A callback function to execute after the delay. It receives the timeout symbol as an argument.ms
: The delay in milliseconds before executing the callback. Default is 0.
Return value
- A unique symbol that identifies the timeout and can be used with
clearTimeout
to cancel it.
Examples
Basic usage
// Log a message after 1 secondconst timeoutSymbol = setTimeout((sym) => { print("This message appears after 1 second");}, 1000);
Canceling a timeout
// Create a timeout that will execute after 5 secondsconst timeoutSymbol = setTimeout((sym) => { print("This will never be printed");}, 5000);
// Cancel the timeout before it executesclearTimeout(timeoutSymbol);
Using the symbol parameter
// The symbol can be used inside the callbackconst timeoutSymbol = setTimeout((sym) => { print(`Timeout with symbol: ${tostring(sym)} has executed`); // The symbol can be used to identify which timeout fired}, 2000);
Zero delay
// With zero delay, the function will execute as soon as possible// (but still asynchronously)setTimeout((sym) => { print("This executes on the next frame");});