javascript - 在将新数组传递给同一个函数后,我无法弄清楚如何停止迭代函数中的数组
问题描述
在我的应用程序中,我连接到新闻服务并拉回一系列文章;我每20分钟做一次。
在这 20 分钟内,我循环浏览我提取的文章数组,每 15 秒从数组中选出一篇新文章。
我的问题是,20 分钟后,我从新闻服务中获取了一个新数组并开始循环遍历该数组。显然,我正在做一个双循环,原始数组加上新数组。
然后,又过了 20 分钟,我正在循环浏览另一组新闻文章……现在总共三篇。
这种情况持续一整天,直到变成一团糟。
我试图弄清楚一旦我得到一个新数组如何停止原始循环:
clearInterval(articleIntervalVar);
newsArticlesArray = null;
但是我没有尝试过任何工作,我无法弄清楚。
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);
}
解决方案
我会使用稍微不同的逻辑,在获得要显示的文章列表时设置间隔,并在此之前清除任何现有间隔。
我还掸掉了所有 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);
推荐阅读
- algorithm - 这个时间复杂度计算对吗?
- java - 您可以将装饰器添加到子类的父方法和变量吗?
- ios - 了解 Here Map iOS SDK 中的错误代码
- php - 在 PHP 中使用不同的访问令牌进行 API 调用
- json - 获取多个复选框值作为角度数组
- .net-core - 将 ServiceStack Redis 使用推送到 Application Insights 依赖项遥测
- mysql - 带有 sql 的 Nodejs
- python - 如何通过 django 视图调度 celery 任务
- json - (Django) 安装夹具“rules.json”时出现问题:“NoneType”对象没有属性“id”
- c# - 如何在c#后面的代码中动态地向html添加新元素