首页 > 解决方案 > 设置嵌套间隔

问题描述

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

标签: javascriptsetintervalintervals

解决方案


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

注意: 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

推荐阅读