@rbxts/jsnatives



setInterval

Repeatedly executes a function with a fixed delay between each call.

Signature

function setInterval(cb: (sym: symbol) => void, ms = 0): symbol

Description

The setInterval function repeatedly calls a callback function with a fixed time delay between each call. It returns a symbol that can be used to stop the interval using clearInterval.

Internally, it uses Roblox's task.delay function to implement the interval behavior.

Parameters

Return value

Examples

Basic usage

// Log a message every second
const intervalSymbol = setInterval((sym) => {
print("This message appears every second");
}, 1000);

Stopping an interval

// Create an interval that executes every 2 seconds
const intervalSymbol = setInterval((sym) => {
print("Interval is running");
}, 2000);
// Later, when you want to stop it:
clearInterval(intervalSymbol);

Self-terminating interval

let count = 0;
const intervalSymbol = setInterval((sym) => {
count++;
print(`Count: ${count}`);
// Stop the interval after 5 executions
if (count >= 5) {
print("Interval complete");
clearInterval(sym); // Using the symbol passed to the callback
}
}, 1000);

Creating a timer

// Create a 10-second countdown timer
let timeLeft = 10;
const timerSymbol = setInterval((sym) => {
print(`Time remaining: ${timeLeft} seconds`);
timeLeft--;
if (timeLeft < 0) {
print("Timer complete!");
clearInterval(sym);
}
}, 1000);
const a = setInterval(() => {
print("Hello, world!"); // will be called every 1 second
}, 1000);