Javascript,如何在循环中每秒同步调用函数?

我很难使用 async/await 使其在循环中同步工作。我的小 showChart 所做的是从服务器请求 10 个项目并使用 plotly 在服务器上绘制它。为了让它像每秒一样,我喜欢把一些睡眠时间最好精确到 1000 毫秒。然而,console.log 似乎每秒打印一次,但 drawChart 函数不是每秒调用一次,而是在最后一分钟显示所有内容。我怎样才能让它每秒画一次?先谢谢了~~!!


/**

 * data comes with { status: '' , message:{ result : [{point:''}, {point:''} ...]}} in json format.  

**/

async function  showChart(url, nextPage ){

        let requestUrl  = url+nextPage;

        let resposne = await fetch(requestUrl);

        let data = await resposne.json();

        data = data.message.result;

        let points = await data.map(e=>e.point);

        console.log(fp1Deltas);

        const num =  fp1Deltas.map(  async delta =>{

           delay(1000);

           // await sleep (1000);

           drawChart(delta);

           console.log( delta);

         });

        console.log('done');       

    }


    const sleep = ms=>{

        return new Promise(resolve => setTimeout(resolve, ms));

    }


 const delay = ( ms)  => {

            var start = new Date().getTime();

            var end = start;

            while( end < start + ms ){

                end = new Date().getTime();

            }

    };


    const  drawChart = point =>{


        Plotly.extendTraces('chart1', {

            y: [

                 [point]

            ]

        }, [0]);

    }


    $(document).ready(function () {

        Plotly.plot('chart1', [{

            y: [],

            type: 'line'

        }]);

        showChart(requestLocation, page);

        // fetchData(requestLocation,page);


    }); // end of document ready


潇潇雨雨
浏览 147回答 1
1回答

Helenr

如果你想循环fplDeltas并调用drawChart每个增量,间隔一秒,你可以这样做:// So we skip the `sleep` the first timelet first = true;for (const delta of fplDeltas) {&nbsp; &nbsp; // Sleep on all but the first&nbsp; &nbsp; if (first) {&nbsp; &nbsp; &nbsp; &nbsp; first = false;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; await sleep(1000);&nbsp; &nbsp; }&nbsp; &nbsp; // Draw the chart&nbsp; &nbsp; drawChart(delta);}由于这是在一个async函数中,因此await sleep(1000)(注意:not delay,您的基于 promise 的sleep)让浏览器允许它进行任何绘图等。这是一个简单的示例,只需在其中添加一个 DOM 元素drawChart:const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));async function example() {&nbsp; &nbsp; const fplDeltas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];&nbsp; &nbsp; let first = true;&nbsp; &nbsp; for (const delta of fplDeltas) {&nbsp; &nbsp; &nbsp; &nbsp; // Sleep on all but the first&nbsp; &nbsp; &nbsp; &nbsp; if (first) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; first = false;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await sleep(1000);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Draw the chart&nbsp; &nbsp; &nbsp; &nbsp; drawChart(delta);&nbsp; &nbsp; }}function drawChart(delta) {&nbsp; &nbsp; const div = document.createElement("div");&nbsp; &nbsp; div.textContent = delta;&nbsp; &nbsp; document.body.appendChild(div);}(async () => {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; await example();&nbsp; &nbsp; &nbsp; &nbsp; console.log("Done");&nbsp; &nbsp; } catch (e) {&nbsp; &nbsp; &nbsp; &nbsp; console.error("Error:", e);&nbsp; &nbsp; }})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript