weixin_33736832 2011-10-26 13:38 采纳率: 0%
浏览 39

ajax settimeout刷新div

I am displaying a graph using jQplot to monitor data. To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below). On the server, a PHP script retrieves the data from a database. On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000). On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message. Monitoring XHR learns that the browser crashes after approximately 200 requests. As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing. This works, but is not an ideal situation. Any better solution to this problem is very much appreciated.

Thanks and regards, JZB

function ajax() {
  $.ajax({
    cache: false,
    url: 'monitor.php',
    data : { x: id },
    method: 'GET',
    dataType: 'json',
    success: onDataReceived,
    error: onDataError
  });

  function onDataReceived(series) {
    $('#chartdiv_bar').html('');
    $.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));

    errorcount = 0;
    setTimeout(ajax, 5000);
  }

  function onDataError(jqXHR, textStatus, errorThrown) {
    errorcount++;
    if (errorcount == 10) {
      alert("No server response:

" + textStatus + "
" + errorThrown);
    } else {
      setTimeout(ajax, 5000);
    }
  }
}
  • 写回答

2条回答 默认 最新

  • larry*wei 2011-10-26 14:05
    关注

    Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.

    you may want to try to clear the current timer and then start the next timer

    var t; //global
    

    In each of your call back functions:

    if(t)      
     clearTimeout(t);
    t = setTimeout(ajax, 5000);
    

    more info on timer here: w3 school

    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)