首页 > 解决方案 > 每 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,所以我想知道最好的方法是什么?

标签: javascript

解决方案


实际上,考虑到涉及异步处理,使用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();

推荐阅读