JSFiddle - React, Tailwind, and code Playground
by Balkanlii
HTML
<head>
<script>
var do_ping = function() {
ping(document.getElementById('pingurl').value).then(function(delta) {
//alert(delta);
}).catch(function(error) {
//alert(String(error));
});
};
</script>
</head>
<body>
<input id='pingurl' type='text' value='http://google.com'></input>
<button onclick='do_ping()'>Ping</button>
</body>
JavaScript
function request_image(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() { resolve(img); };
img.onerror = function() { reject(url); };
img.src = url + '?random-no-cache=' + Math.floor((1 + Math.random()) * 0x10000).toString(16);
});
}
function ping(url, multiplier) {
return new Promise(function(resolve, reject) {
var start = (new Date()).getTime();
var response = function() {
var delta = ((new Date()).getTime() - start);
delta *= (multiplier || 1);
if (delta>99) resolve(delta);
else reject(delta);
};
request_image(url).then(response).catch(response);
console.log(request_image(url).then(response).catch(response))
// Set a timeout for max-pings, 5s.
setTimeout(function() { reject(Error('Timeout')); }, 5000);
});
}