每60秒更新一次数据-Vanilla JS SPA

Nem*_*a G 1 javascript

我有一个呈现一些html的函数,我不知道如何在这里调用setInterval函数,每60秒调用一次render func。

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;
Run Code Online (Sandbox Code Playgroud)

我真的不能把render函数放进去setInterval,所以我想知道最好的方法是什么?

T.J*_*der 6

实际上,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);
}
Run Code Online (Sandbox Code Playgroud)

该代码假定即使一次调用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();
Run Code Online (Sandbox Code Playgroud)