在函数中使用 set interval 和 fetch [英] Using set interval and fetch in a function
问题描述
创建一个函数startShowingMessage
,它接受两个参数:一个元素和一个作为URL 的字符串.该函数将使用 setInterval
每 1 秒执行以下任务:获取 URL 并将响应文本放入提供的元素的文本内容中.
我制作了函数并且获取工作,但我不知道如何在同一个函数中设置间隔,而不必调用另一个函数.
异步函数 startShowingMessage(elem, url){const 响应 = 等待 fetch(url);const text = 等待 response.text();elem.textContent = 文本;}
由于没有间隔,所以函数部分起作用.
您可以根据需要使用 setInterval
function startShowingMessage(elem, url){setInterval(异步函数(){const 响应 = 等待 fetch(url);const text = 等待 response.text();elem.textContent = 文本;}, 1000);}
如果你想了解更多关于它这里是W3Schools>
或者可以找到官方文档这里是 MDN 文档,如 3limin4t0r 所建议的
Create a function startShowingMessage
that takes two parameters: an element and a string that is a URL. The function will use setInterval
to make the following task every 1s: fetch the URL and put the response text into the text content of the provided element.
I made the function and the fetch works, but i don't know how to set interval in the same function, without having to call another function.
async function startShowingMessage(elem, url){
const response = await fetch(url);
const text = await response.text();
elem.textContent = text;
}
The functions works partially because there is no interval.
you can use setInterval
for your need
function startShowingMessage(elem, url){
setInterval(async function(){
const response = await fetch(url);
const text = await response.text();
elem.textContent = text;
}, 1000);
}
if you want to learn more about it here it is on W3Schools
Or the official documentation can be found here on MDN documentation as suggested by 3limin4t0r
这篇关于在函数中使用 set interval 和 fetch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!