首页 > 解决方案 > 在将新数组传递给同一个函数后,我无法弄清楚如何停止迭代函数中的数组

问题描述

在我的应用程序中,我连接到新闻服务并拉回一系列文章;我每20分钟做一次。

在这 20 分钟内,我循环浏览我提取的文章数组,每 15 秒从数组中选出一篇新文章。

我的问题是,20 分钟后,我从新闻服务中获取了一个新数组并开始循环遍历该数组。显然,我正在做一个双循环,原始数组加上新数组。

然后,又过了 20 分钟,我正在循环浏览另一组新闻文章……现在总共三篇。

这种情况持续一整天,直到变成一团糟。

我试图弄清楚一旦我得到一个新数组如何停止原始循环:

但是我没有尝试过任何工作,我无法弄清楚。

newsFunction();
newsIntervalVar = setInterval(newsFunction, 1200000);

function newsFunction() {
    xmlHttpNewsObject = GetXmlHttpObject();

    if (xmlHttpNewsObject === null){
        alert ("Browser does not support HTTP Request");
        return;
    }

    var url = "";
    xmlHttpNewsObject.open("GET", url, true);
    xmlHttpNewsObject.onreadystatechange = getTheNews;
    xmlHttpNewsObject.send(null);
}

function getTheNews(){
    if (xmlHttpNewsObject.readyState == 4 && xmlHttpNewsObject.status == 200){
        var newsArticlesArray = JSON.parse(xmlHttpNewsObject.responseText).articles
        drawTheNews(newsArticlesArray);
        return;
    }
}

function drawTheNews(newsArticlesArray) {
    var news = document.getElementById('news');
    var numberOfArticles = newsArticlesArray.length;
    var i = 0;
    news.innerHTML = newsArticlesArray[i].title);
    var articleIntervalVar = setInterval(function () {
        i++;
        if (i === numberOfArticles) i = 0;
        news.innerHTML = newsArticlesArray[i].title);
    }, 15000);
}

标签: javascriptarraysxmlhttprequest

解决方案


我会使用稍微不同的逻辑,在获得要显示的文章列表时设置间隔,并在此之前清除任何现有间隔。

我还掸掉了所有 20 世纪的xmlHttp文学作品,并用fetch:)

const url = "...";
const newsElem = document.getElementById('news'); // cache your element instead of accessing it every time
let articles = [];
let articleInterval = null;

const newsFunction = async() => {
  try {
    const response = await fetch(url)
    articles = await response.json();
    clearInterval(articleInterval); // Clear the existing interval here
    articleInterval = setInterval(drawTheNews, 15000); // Set the new interval
  } catch (err) {
    console.log("Error getting the news : ", err)
  }
}

const drawTheNews = () => {

  const article = articles.pop();

  if (!article) {
    console.log("Depleted all news!")
    clearInterval(articleInterval)
    return;
  }

  newsElem.innerHTML = article.title
}

newsFunction();
setInterval(newsFunction, 1200000);


推荐阅读