制作嵌套集间隔

make nested set interval

我有一个来自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);  
}

// 创建第一个区间 一个(); 注意:需要这样的代码,例如从另一个调用设置间隔函数。 我需要 o/p 作为 答:10:32:34 乙:10:33:4 答:10:33:4 答:10:33:34

您应该将每个间隔分开并将它们分配给一个全局变量,以便在需要时清除它们。

注意: setTimeout()setInterval() 不是 reliable for exact timing operation,对于那种类型的任务,你应该每次都参考时钟时间通过 Date(),也许使用更小的间隔检查。备选方案是 requestAnimationFrame()web worker.

// 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();

  • 30 秒后回调 A 被调用(全局时间 30 秒),B 被实例化并延迟 60 秒
  • 30 秒后回调 A 被调用(全球时间 60 秒)并且 B 在开始前有 30 秒
  • 30s后调用A调用B(全局时间90s)

现在,每 30 秒:

  • 一个
  • AB
  • 一个
  • AB
  • ...等等