javascript - 设置嵌套间隔
问题描述
我有一个来自 set interval 函数的函数调用,并且每 1 mt 执行一次。但现在它的工作取决于父迭代 0.5 mt。
let intervalA;
let intervalB;
var timeInMinuts;
const a = () =>
// Assign the interval to global variable
timeInMinuts = 60000;
intervalA = window.setInterval(function() {
const today = new Date();
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('A: ' + time);
// Check if event is assigned and then instantiate the intevalB
if (!intervalB) b();
} , 30000);
const b = () => {
// Assign the interval to global variable
intervalB = setInterval(function() {
const today = new Date();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('B: ' + time);
}, timeInMinuts);
}
// 创建第一个区间 a(); 注意:需要像这样的代码,比如从另一个调用一个设置的间隔函数。我需要 o/p 作为 A: 10:32:34 B: 10:33:4 A: 10:33:4 A: 10:33:34
解决方案
您应该分隔每个间隔并将它们分配给全局变量,以便在需要时清除它们。
注意: setTimeout()
并且对于精确的定时操作setInterval()
并不可靠,对于那种类型的任务,您应该每次通过 参考时钟时间,也许使用更小的间隔检查。替代方案是和网络工作者。Date()
requestAnimationFrame()
// Store the interval in global variables so them are reachable to be cleared from any function
let intervalA;
let intervalB;
const a = () =>
// Assign the interval to global variable
intervalA = window.setInterval(function() {
const today = new Date();
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('A: ' + time);
// Check if event is assigned and then instantiate the intevalB
if (!intervalB) b();
} , 30000);
const b = () => {
const timeInMinuts = 60000;
// Assign the interval to global variable
intervalB = setInterval(function() {
const today = new Date();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('B: ' + time);
}, 60000);
}
// Create first interval
a();
- 30s 后回调 A 被调用(全局时间 30s)并且 B 被延迟 60s
- 30秒后回调A被调用(全球时间60秒),B在开始前有30秒
- 30s后调用A,调用B(全球时间90s)
现在,每 30 秒:
- 一个
- AB
- 一个
- AB
- ...ETC
推荐阅读
- python - 如何在 Python 中使用 Selenium 访问 div 标签内的文本?
- python - SQLAlchemy - base.metadata.tables 中的表没有属性“映射器”
- python-3.x - 如何使用 Python3 多处理来追加列表?
- string - 如何将字符串的 charAtIndex 转换为 ASCII 等效 int 值
- php - Laravel:数据未出现在视图中
- amazon-web-services - CloudFormation中如何修改多行参数?
- python - 在 Python 中重置索引
- c# - 在 NetStandard 类中找不到类型或命名空间名称“DbContext”
- ios - 没有同时读取数据GCDAsyncSocket
- ios - 通过委托将数据传递给各种视图控制器