ping
Sends a ping request to the given URL and returns the response time in ms.
1/**
2 * Sends a ping request to the given URL and returns the response time in ms.
3 *
4 * @param url - The URL to ping.
5 * @param timeout - Optional timeout in milliseconds (default: 5000).
6 * @returns A promise resolving to the response time in milliseconds,
7 * or null if the request failed or timed out.
8 */
9export async function ping(url: string, timeout = 5000): Promise<number | null> {
10 const controller = new AbortController();
11 const id = setTimeout(() => controller.abort(), timeout);
12 const start = performance.now();
13
14 try {
15 await fetch(url, { method: 'HEAD', signal: controller.signal });
16 return Math.round(performance.now() - start);
17 } catch {
18 return null;
19 } finally {
20 clearTimeout(id);
21 }
22}
Non-Intrusive Method
Uses the
HEAD
method, which avoids downloading the full response body, making it lightweight and bandwidth-efficient.Accurate Timing with
performance.now()
Measures latency with high-resolution timestamps, offering more precise response time than
Date.now()
.Built-in Timeout Handling
Uses
AbortController
to ensure that the request does not hang indefinitely, allowing fine-grained timeout control.Graceful Failure Handling
Returns
null
on network errors or timeouts instead of throwing, making it safer for use in critical workflows.
Tests | Examples
1// jest-environment-node
2
3test('ping - returns response time for a reachable URL', async () => {
4 const time = await ping('https://www.google.com');
5 expect(typeof time).toBe('number');
6 expect(time).not.toBeNull();
7});
8
9test('ping - returns null for an unreachable URL', async () => {
10 const time = await ping('https://nonexistent.domain.example');
11 expect(time).toBeNull();
12});
13
14test('ping - returns null if request times out', async () => {
15 const time = await ping('https://www.google.com', 1); // very short timeout
16 expect(time).toBeNull();
17});
Common Use Cases
Network Latency Monitoring
Measure response time to a server or API endpoint for diagnostics or performance metrics.
Server Health Checks
Periodically verify availability of backend services with minimal load.
User Connectivity Assessment
Assess real-time connectivity quality in browser-based applications before performing large operations.
Dynamic Timeout Calibration
Use response time measurements to adjust application timeouts or polling intervals programmatically.