0

The following script is supposed to do the following:

At page load, it will set a timeout of 20 seconds, then the desired content will be updated in an ajax call automatically. If the user clicks a button that says RELOAD, it will call to function reloadContent() and thus clearing the timeout and setting one again.

So basically, it will should restart the timeout if the user manually reloaded, to avoid too close calls.

It works half, because the timer seems to be reset, but the reloadContentTimeout() will execute after 10 seconds of the manually loaded action, which is half the timeout time.

Am I doing something wrong?

Thanks!

  /**
   *  Reload content
   */
  function reloadContent(elementId) {
    $(elementId).load(window.location.href+' '+elementId+' > *');
    clearTimeout(timeoutId);
    reloadContentTimeout(false);
  }

  /**
   * Reload content every X seconds (20)
   */
  var timeoutId;
  function reloadContentTimeout(now)
  {
    now = (typeof now === 'undefined' ? true : now);
    if( now ) {
      reloadContent('#table-content');
    }
    timeoutId = setTimeout(reloadContentTimeout, 1000 * 20);
  }
  reloadContentTimeout(false);
4

2 回答 2

3

因为您调用reloadContentTimeout了两次,这会重新分配timeoutId. 其中一个 ID 不会被清除,并且事件的触发频率超出了应有的频率。让我们稍微展开您的调用堆栈:

if (now) {
    $(elementId).load();
    clearTimeout(timeoutId);
    // this reassigns timeoutId
    reloadContentTimeout(false)
}
// this is where timeoutId is assigned.  It gets assigned
// by this call, but also the call above.
timeoutId = setTimeout(reloadContentTimeout, 1000 * 20);

我会切入正题:这将解决问题。

if (now) {
    /* snip */
}
else {
    timeoutId = /* snip */
}
于 2013-10-09T20:18:34.237 回答
1

请检查您的通话顺序

  • 每次调用 reloadContentTimeout 时都会开始一个新的超时(对于可能的参数值“未定义”和“假”)
  • 20 秒后,您重新加载内容,这将在清除旧内容后开始新的超时(这非常无用,因为计时器已经触发)。然后您开始另一个超时并重新分配 timeoutId 而不清除您之前创建的超时。现在你有两个超时运行,这将在每次超时完成后连续发生

检查@Explosion Pills 的答案。它将帮助您解决问题

于 2013-10-09T20:22:16.263 回答