【问题标题】:How to refresh div every 10 seconds automatically and stop when click on button?如何每 10 秒自动刷新一次 div 并在单击按钮时停止?
【发布时间】:2016-05-30 11:14:38
【问题描述】:

当我点击ul标签时,我有一个按钮将显示块。
我希望ul 中的数据会在 10 秒后自动刷新。数据来自我需要点击的 api。
当点击停止按钮时,数据不会被刷新。

function dummy(){ 
    setTimeout("checkalerts()",10000); 
} 

function checkalerts() { 
    $.ajax({
      method: "POST",
      url: "/messages/get/"+contactid,
      data: { since: since }
    })
      .done(function( msg1 ) {

      var el = $('<li class="message right appeared">
<div class="avatar"><img src="'+url+'/service/getUserImage/'+msg1[i].userID +'/60"/></div>
<div class="text_wrapper">
<div class="text">'+msg1[i].message+'</div></div></li>');
                 $(".chat_window ul").append(el);

    });

    }

【问题讨论】:

  • 所以你想停止超时?然后只需将 setTimeout 分配给一个变量,如果要清除它,请调用“clearTimeout(variable)”。检查w3schools.com/jsref/met_win_cleartimeout.asp
  • 只需将setTimeout的返回值赋值给一个变量,点击按钮时使用clearTimeout即可。
  • 您可能想使用setInterval 而不是setTimeout。将其分配给变量并单击按钮后将其清除
  • 是的,我想在点击时停止计时器并在点击开始时再次重新启动它,它将每 10 秒引用一次而不点击任何地方
  • 如何清除区间值?

标签: javascript refresh


【解决方案1】:

跟踪当前的setTimeout。它返回一个也可以再次取消的 ID:MDN

在您的 ajax 成功回调中,只需再次设置超时并保存 ID。 当您按下停止按钮时,取消超时。

// assign to the start button
function dummy() {  
  fetch();
}

// assign to stop button
function stop() {
    clearTimeout(timeoutId);
}

function fetch() {
// do your ajax stuff here
  output.innerHTML = 'fetched ' + new Date().getSeconds();

  // and in the success callback, reset time timeout
  timeoutId = setTimeout(fetch, 1000);
}

btnStart.addEventListener('click', dummy);
btnStop.addEventListener('click', stop);

工作演示:Fiddle

【讨论】:

  • clearTImeout 对我不起作用。当我调用停止函数时,它调用停止函数但不清除 timeoutid 值该怎么办?
猜你喜欢
  • 1970-01-01
  • 2021-01-22
  • 2022-11-26
  • 1970-01-01
  • 2012-01-31
  • 2022-07-06
  • 2016-11-07
  • 1970-01-01
相关资源
最近更新 更多