You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为这段JavaScript代码添加时间间隔以实现自动数据拉取?

为数据拉取代码添加时间间隔实现自动刷新

方法一:使用setInterval(简单直接)

直接用setInterval指定固定时间间隔重复调用fetch函数,适合对请求响应速度有把握的场景:

function fetch(){
  $.ajax({
    type: 'POST',
    url: 'resultsget.php',
    dataType: 'json',
    success: function(response){
      $('#content').html(response).iCheck({checkboxClass: 'icheckbox_flat-green',radioClass: 'iradio_flat-green'});
    }
  });
}

// 每5秒执行一次数据拉取(时间单位为毫秒,5000ms=5s)
setInterval(fetch, 5000);

注意:如果请求响应较慢,setInterval会无视前一次请求是否完成,到点就发起新请求,可能导致多个请求同时运行,给服务器和前端带来额外压力。


方法二:使用递归setTimeout(更稳妥)

在请求完成(成功或失败)后再设置下一次调用,确保每次请求都在前一次结束后才发起,避免请求堆积:

function fetch(){
  $.ajax({
    type: 'POST',
    url: 'resultsget.php',
    dataType: 'json',
    success: function(response){
      $('#content').html(response).iCheck({checkboxClass: 'icheckbox_flat-green',radioClass: 'iradio_flat-green'});
      // 请求成功后,5秒后发起下一次拉取
      setTimeout(fetch, 5000);
    },
    error: function(){
      // 可选:请求失败时也重试,避免自动刷新中断
      setTimeout(fetch, 5000);
    }
  });
}

// 首次调用启动自动刷新循环
fetch();

停止自动拉取的方法

如果需要随时停止自动刷新,需要保存定时器ID并调用清除方法:

针对setInterval的情况:

// 保存定时器ID
const intervalId = setInterval(fetch, 5000);

// 需要停止时执行
// clearInterval(intervalId);

针对递归setTimeout的情况:

let timeoutId;

function fetch(){
  $.ajax({
    type: 'POST',
    url: 'resultsget.php',
    dataType: 'json',
    success: function(response){
      $('#content').html(response).iCheck({checkboxClass: 'icheckbox_flat-green',radioClass: 'iradio_flat-green'});
      timeoutId = setTimeout(fetch, 5000);
    },
    error: function(){
      timeoutId = setTimeout(fetch, 5000);
    }
  });
}

fetch();

// 需要停止时执行
// clearTimeout(timeoutId);

内容的提问来源于stack exchange,提问作者Sirh Eazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:01:47