您可以使用JavaScript中的setInterval函数来定时发送http请求,并使用XMLHttpRequest对象发送http请求。

以下是一个示例代码,每隔2秒发送一个http请求,并在请求完成后关闭连接:

var intervalId = setInterval(function() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://example.com/api?id=1', true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      // 处理请求成功的响应数据
      console.log(xhr.responseText);
      xhr = null; // 释放xhr对象
    }
  };
  xhr.send();
}, 2000);

// 请求完成后关闭连接
setTimeout(function() {
  clearInterval(intervalId);
}, 10000); // 10秒后关闭连接

在上面的代码中,setInterval函数用于定时执行代码块,XMLHttpRequest对象用于发送http请求。请求完成后,可以在onreadystatechange事件处理程序中处理响应数据。setTimeout函数用于在一定时间后关闭连接,这里设置为10秒。

请注意,在实际使用中,您需要将http://example.com/api?id=1替换为您实际的API地址,并根据需要修改请求参数和处理响应的代码

标签: 科技


原文地址: https://cveoy.top/t/topic/hyBj 著作权归作者所有。请勿转载和采集!