Skip to content

Core\Time\Duration::milliseconds

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$n milliseconds is longer than a Duration can 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";
Output
1s500ms
1500
-250ms

Too 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";
}
Output
9223372036854
Core\Time\Duration::milliseconds(): this duration is longer than `Core\Time\Duration` can hold

Wait 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;
}
Output
attempt 1: wait 100ms
attempt 2: wait 200ms
attempt 3: wait 400ms
attempt 4: wait 800ms
attempt 5: wait 1s600ms
attempt 6: wait 2s