首页 > 解决方案 > 使用 setTimeOut 时如何动态更新间隔?

问题描述

我想在 5 秒后关闭弹出窗口。那么如何setTimeOut动态更新间隔(或点击功能)?

var myWindow = window.open("", "myWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
setTimeout(function(){ 
  myWindow.close() 
}, 3000);

标签: jquery

解决方案


据我了解,您想开始超时,如果用户在此期间以某种方式进行交互,请将超时延长至 10 秒。

您无法更改运行超时,但您可以停止它并以新的延迟重新启动它。

如果您保存自第一次超时开始以来经过的时间,您可以计算出新的延迟时间总计为 10 秒。

在我的示例中,如果您按下start一次,它将运行 5 秒。如果在 5 秒内再次按下它,它将以适当的延迟重新开始超时,因此总共加起来为 10 秒

let timeout = null;
let timestamp = null;
$('#start').click(function() {
  let time = 5000;
  if (timestamp === null) {
    // save the current timestap 
    timestamp = +new Date;
  } else {
    // subtract the elapsed time since `timestamp` from the desired 10 seconds and restart the timer
    time = 10000 - ((+new Date) - timestamp);
    timestamp = null;
    $('#start').prop('disabled', true);
  }
  
  out(`timeout started with ${time} ms`);
  clearTimeout(timeout);
  timeout = setTimeout(function() {
    timestamp = null;
    out('done');
    $('#start').prop('disabled', false);
  }, time);
});

function out(text) {
  $('#output').append(text + '<br/>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="start">start timeout</button><br/>
<div id="output"></div>


推荐阅读