Time and Timing
Overview
Timing in BattleScript is provided by language keywords, not by a standard library. Use after to run something once after a delay and every to run something repeatedly, optionally with a limit on the number of repeats. Timers can be assigned to a variable and controlled later with stop, start, resume and cancel.
To read the current device clock (rather than schedule work), use std::time.now(), which returns an integer you can subtract from a later reading to measure elapsed time. Scheduling itself is done through the keywords described below.
Timers
The after and every keywords schedule one-off and repeating work. Both take a delay/interval expression in milliseconds followed by a block of code.
after
Description: Run a block once after a delay (in milliseconds).
Syntax: after expression { ... }
Example:
// Run once after 2 seconds
after 2000 {
std::console.log("2 seconds passed");
}every
Description: Run a block repeatedly at a fixed interval (in milliseconds). Add limit n to cap the number of runs, or keep to retain the timer across state changes.
Syntax: every expression [limit n] [keep] { ... }
Examples:
// Log a message every 500ms
every 500 {
std::console.log("tick");
}
// Run 5 times, then auto-stop
every 1000 limit 5 {
std::console.log("repeat with limit");
}
// Keep the timer running across state changes
every 1000 keep {
std::console.log("persistent tick");
}Controlling timers
Assign a timer to an int variable to control it later. Use stop to pause it, start to (re)start it, resume to continue a stopped timer and cancel to remove it. Each of these can also be used bare (e.g. cancel;) from inside a timer block to act on the current timer.
Assign and control a timer
// Assign a repeating timer to a variable
int t = every 1000 {
std::console.log("tick");
};
stop t; // pause the timer
start t; // (re)start the timer
resume t; // resume after stopping
cancel t; // remove the timer entirelyCancel from inside a block
Description: Use a bare cancel; inside an every block to stop further repeats. A limit clause auto-stops without any explicit call.
int count = 0;
every 1000 {
count += 1;
std::console.log("count:", count);
if (count == 3) {
// Stop further repeats
cancel;
}
}