JavaScript function to make ping command
- User
JavaScript function to make ping command
- Assistant
Here is an example of a JavaScript function that can simulate a ping command:
function pingHost(hostname) { return new Promise((resolve, reject) => { const start = new Date().getTime(); const xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status === 200) { const latency = new Date().getTime() - start; resolve(`Ping successful. Latency: ${latency}ms`); } else { reject(`Ping failed. Status: ${xhr.status}`); } }; xhr.onerror = function() { reject(`Ping failed. Network error.`); }; xhr.open('GET', `https://${hostname}`, true); xhr.send(); }); } // Usage example pingHost('example.com') .then(response => console.log(response)) .catch(error => console.error(error));In this code, a
pingHostfunction takes in the hostname as an argument and returns a Promise. It creates a newXMLHttpRequestobject, attaches event handlers foronloadandonerrorevents, and opens a GET request to the specified hostname.The
onloadfunction checks if the status of the request is 200 (indicating a successful response). If successful, it calculates the latency as the time difference between starting the request and receiving the response, and resolves the Promise with a success message and the latency value.If the status is not 200, it rejects the Promise with an error message indicating the status code.
If the request encounters a network error, the
onerrorfunction is triggered, and the Promise is rejected with a network error message.Finally, the function
pingHostis called with the desired hostname, and success and error handlers are attached using the.thenand.catchmethods respectively. The result of the ping will then be logged to the console.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.