javascript - 每 60 秒更新一次数据 - vanilla js SPA
问题描述
我有这个渲染一些 html 的函数,我不知道如何在这里调用 setInterval 函数,每 60 秒后调用一次渲染函数
const Home = {
render: async () => {
const cryptos = await getAllCryptos();
const view = `
<section class="section">
<table>
${cryptos.data.map(crypto =>
`<tr>
<td class="name"><a href="/src/#/crypto/${crypto.id}">${crypto.name}</a> </td>
<td>${crypto.symbol}</td>
<td>${crypto.quote.USD.price}</td>
<td>${crypto.quote.USD.percent_change_24h}</td>
</tr>`
)}
</table>
</section>
`;
return view
}
};
export default Home;
我真的不能把渲染功能放在里面setInterval
,所以我想知道最好的方法是什么?
解决方案
实际上,考虑到涉及异步处理,使用setInterval
会很混乱。render
相反,一系列链接setTimeout
可能是最好的:
const RENDER_INTERVAL = 60000; // 60 seconds in milliseconds
function handleRender() {
Home.render()
.then(html => {
// ...use the HTML...
})
.catch(error => {
// ...report the error...
})
.finally(scheduleRender);
}
function scheduledRender() {
setTimeout(handleRender, RENDER_INTERVAL);
}
该代码假定您想要继续,即使一次调用Home.render
失败。
如果你想使用从最后一次调用开始render
到结束的 60 秒(上面是结束后的 60 秒),你会做更多的逻辑:
const RENDER_INTERVAL = 60000; // 60 seconds in milliseconds
let lastRenderStart = 0;
function handleRender() {
lastRenderStart = Date.now();
Home.render()
.then(html => {
// ...use the HTML...
})
.catch(error => {
// ...report the error...
})
.finally(scheduleRender);
}
function scheduledRender() {
setTimeout(handleRender, Math.max(0, RENDER_INTERVAL - (Date.now() - lastRenderStart));
}
handleRender();
推荐阅读
- sql - pgSQL FULL OUTER JOIN 'WHERE' 条件
- tensorflow - 如何在张量流中的两个选定维度上执行 tf.nn.softmax?
- c++ - 在 Linux 下使用 C++ 获取显示器的制造商和产品 ID 和序列号
- typescript - 使用为 S3 构建的预签名 URL 到 CloudFront 的 S3 PutObject 会导致错误
- android - 未解决的参考“设计”
- emacs - 将 ipynb notebook 转换为 org 并在 emacs 中执行
- c++ - 向量
> 尺寸 - excel - 计算列中的值忽略重复项
- javascript - 在 NPM/GULP 中编译测试时如何保留文件夹结构?
- java - 简单的休眠映射问题