jquery - 使用 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);
解决方案
据我了解,您想开始超时,如果用户在此期间以某种方式进行交互,请将超时延长至 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>
推荐阅读
- javascript - 使用 mouseX/Y、if 语句和图像在 p5.js 中创建迷宫
- java - 如何使用 Google guava 缓存库单独获取密钥
- php - 操作 for 循环以仅使用特定变量运行代码
- java - 如何获取批处理文件以自动填充 Java 代码提示的输入
- python - “[WinError 10061] 由于目标机器主动拒绝,无法建立连接”
- angular - 角度路由未显示组件内容
- json - 在 Swift 中可选时将 JSON 中的类型不匹配键解码为 nil 的一般策略
- fortran - 为什么以数组作为输入的子例程比具有自动局部数组的相同子例程提供更快的性能?
- php - php api 不发送任何消息来响应本机应用程序
- node.js - 使用 Cloud Firestore 更新触发器删除 Firestore 中的文档