Core\Time\Duration::milliseconds
Core\Time\Duration::milliseconds(int $n): Core\Time\DurationCore\Time\Duration::milliseconds( int $n, ): Core\Time\Duration
Creates a duration of a given number of milliseconds. A millisecond is one thousandth of a second.
Use it when the number of milliseconds is known only while the program runs, for example when a timeout comes from a setting or a delay grows with each retry. When the number is fixed, write the duration directly in the code, such as 250ms. A negative number gives a negative duration. The number can be up to 9,223,372,036,854 milliseconds, which is about 292 years. A larger number throws a RuntimeError.
toString shows the duration in the largest units that fit. So 1500 milliseconds prints as 1s500ms.
Parameters
$nintThe count of milliseconds; negative for a duration that runs backwards.
Return value
Returns Core\Time\Duration. A Duration of $n × 1 000 000 nanoseconds.
Errors
RuntimeError$nmilliseconds is longer than aDurationcan hold — past ±2⁶³ nanoseconds.
Examples
From a computed number
<?nvs// Shows how to create a duration from a number of milliseconds that the program computes.
int $frames = 60;Core\Time\Duration $animation = Core\Time\Duration::milliseconds($frames * 25);
// 1500 milliseconds is 1 second and 500 milliseconds. This prints 1s500ms.echo $animation->toString(), "\n";
// `toMilliseconds` returns the number again. This prints 1500.echo $animation->toMilliseconds(), "\n";
// A negative number gives a negative duration. This prints -250ms.echo Core\Time\Duration::milliseconds(-250)->toString(), "\n";1s500ms1500-250msToo many milliseconds
<?nvs// Shows what happens when the number of milliseconds is too large for a duration.
// 9223372036854 is the largest number that fits. This prints it again.echo Core\Time\Duration::milliseconds(9223372036854)->toMilliseconds(), "\n";
// One more millisecond does not fit, so `milliseconds` throws a `RuntimeError`.try { Core\Time\Duration::milliseconds(9223372036855);} catch (RuntimeError $e) { echo $e->message, "\n";}9223372036854Core\Time\Duration::milliseconds(): this duration is longer than `Core\Time\Duration` can holdWait longer after each retry
<?nvs// Computes how long a program waits before each new attempt, when a request to a server keeps failing.
int $delayMillis = 100;int $attempt = 1;while ($attempt <= 6) { Core\Time\Duration $wait = Core\Time\Duration::milliseconds($delayMillis);
// The wait is never longer than 2 seconds. if ($wait->compareTo(2s) > 0) { $wait = 2s; }
// The wait doubles each time. This prints 100ms, 200ms, 400ms, 800ms, 1s600ms and 2s. echo 'attempt ', $attempt, ': wait ', $wait->toString(), "\n"; $delayMillis = $delayMillis * 2; $attempt = $attempt + 1;}attempt 1: wait 100msattempt 2: wait 200msattempt 3: wait 400msattempt 4: wait 800msattempt 5: wait 1s600msattempt 6: wait 2s