JS 模拟 ping IP地址

测了一个可用的:

function ping_ip (ip) {
  let img = new Image()
  let start = new Date().getTime()
  let isC = true
  let hasFinish = false
  return new Promise((resolve, reject) => {
    img.onload = function () {
      if (!hasFinish) {
        hasFinish = true
        resolve('success')
      }
    }
    img.onerror = function () {
      if (!hasFinish) {
        if (!hasC) {
          resolve('success')
        } else {
          resolve('failed')
        }
        hasFinish = true
      }
    }
    setTimeout(function () {
      if (!hasFinish) {
        hasFinish = true
        resolve('failed')
      }
    }, 3000)
    img.src = `http://${ip}/${start}`
    isC = false
    console.log('start')
  })
}

你可能感兴趣的:(随笔,javascript)