停止并重新开始一个间隔(或超时?)

stopping and restarting an interval (or timeout?)

我有一个脚本可以检查小时并在满足某些条件时在 div 中创建元素(如果小时在 6 点和 8 点之间,如果小时在 19 点和 8 点之间,它会创建一个早上列表20 它创建了一个晚间列表。问题是,我在脚本上设置了超时和间隔(不同的测试,不是同时在一起)让它不断检查小时,然后继续追加到 ul。我希望函数不断被调用以保持最新,但我希望它在创建新元素之前停止 运行ning 如果满足小时参数。我对此有困难...这是我的代码。

我的编码速度快于我的学习...再次感谢您提供的任何帮助,阅读此处的其他文章对弄清楚如何使该应用程序的各个部分工作有很大帮助。不过,我偶尔会 运行 遇到一个似乎无法解决的问题。

morningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];
eveningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];

const hour = new Date().getHours();

function listMeds() {
    if (hour >= 6 && hour <= 8) {
        clearInterval(listMeds);
    } else if (hour >= 19 && hour <= 20) {
        clearInterval(listMeds);
    } else {}

    if (hour >= 6 && hour <= 8) {
        let morningMeds = document.getElementById('morning-meds-list');
        mornMed = document.createElement('li');
        morningMedsList.forEach(function (med, index) {
            clone = mornMed.cloneNode();
            clone.textContent = (index +1) + '. ' + med;
            morningMeds.appendChild(clone);
        });
    } else if (hour >= 19 && hour <= 23) {
        let eveningMeds = document.getElementById('evening-meds-list');
            eveMed = document.createElement('li');
            eveningMedsList.forEach(function (med, index) {
                clone = eveMed.cloneNode();
                clone.textContent = (index +1) + ': ' + med;
                eveningMeds.appendChild(clone);
            });
        }

    console.log('test');
}

setInterval(listMeds, 5000);

您需要将间隔分配给全局变量,并在对 clearInterval() 的调用中使用它。

您还应该在 listMeds 函数中获取小时。否则,您将始终检查页面加载的时间,而不是间隔函数为 运行.

的当前时间

morningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];
eveningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];

let medsInterval = setInterval(listMeds, 5000);

function listMeds() {
  const hour = new Date().getHours();
  console.log(hour);
  if (hour >= 6 && hour <= 8) {
    clearInterval(medsInterval);
  } else if (hour >= 19 && hour <= 20) {
    clearInterval(medsInterval);
  } else {}

  if (hour >= 6 && hour <= 8) {
    let morningMeds = document.getElementById('morning-meds-list');
    mornMed = document.createElement('li');
    morningMedsList.forEach(function(med, index) {
      clone = mornMed.cloneNode();
      clone.textContent = (index + 1) + '. ' + med;
      morningMeds.appendChild(clone);
    });
  } else if (hour >= 19 && hour <= 23) {
    let eveningMeds = document.getElementById('evening-meds-list');
    eveMed = document.createElement('li');
    eveningMedsList.forEach(function(med, index) {
      clone = eveMed.cloneNode();
      clone.textContent = (index + 1) + ': ' + med;
      eveningMeds.appendChild(clone);
    });
  }

  console.log('test');
}
Morning Meds
<ul id="morning-meds-list"></ul>
Evening Meds
<ul id="evening-meds-list"></ul>

我认为关键是您不想清除该间隔,否则您将如何再次启动它?我认为您只需要一个标志来检查是否已经打印了列表,并且在这种情况下不要再次打印。超出时间范围清空列表,重新更改flag,依此类推:

const morningMedsList = [
  'morning_med1',
  'morning_med2',
  'morning_med3',
  'morning_med4',
  'morning_med5',
];
const eveningMedsList = [
  'evening_med1',
  'evening_med2',
  'evening_med3',
  'evening_med4',
  'evening_med5',
];
const medsHours = [6, 7, 8, 19, 20, 21, 22, 23];
const morningContainer = document.getElementById('morning-meds-list');
const eveningContainer = document.getElementById('evening-meds-list');

let wasWithinRange = false;

let hour = new Date().getHours();

function listMeds() {
  hour = new Date().getHours();
  console.log('CHECKING TIME, HOUR:', hour);

  if (!medsHours.includes(hour) && wasWithinRange) {
    console.log('RESETTING FLAG');
    wipeNodes([morningContainer, eveningContainer]);
    wasWithinRange = false;
  }

  if (hour >= 6 && hour <= 8 && !wasWithinRange) {
    console.log('CREATING MORNING LIST');
    createElems(morningContainer, morningMedsList);
    wasWithinRange = true;
  }

  if (hour >= 19 && hour <= 23 && !wasWithinRange) {
    console.log('CREATING EVENING LIST');
    createElems(eveningContainer, eveningMedsList);
    wasWithinRange = true;
  }
}

setInterval(listMeds, 5000);

function createElems(elem, list) {
  const item = document.createElement('li');

  list.forEach(function(med, index) {
    const clone = item.cloneNode();
    clone.textContent = index + 1 + '. ' + med;
    elem.appendChild(clone);
  });
}

function wipeNodes(elems) {
  elems.forEach((elem) => (elem.innerHTML = ''));
}
/* 
TESTING
*/

const btn = document.querySelector('button');
btn.onclick = () => {
  hour = Number(prompt('SET HOUR:'));
};
<div id="morning-meds-list"></div>
<div id="evening-meds-list"></div>
<button>SET HOUR MANUALLY FOR TESTING</button>

我放置了一个按钮来手动提示输入小时值,以便您可以测试这是否是您期望的行为。