Javascript,如何在循环中每秒同步调用函数?
Javascript, how can I synchronously call function every second in the loop?
我很难使用 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
如果你想遍历 fplDeltas
并用每个增量调用 drawChart
,间隔一秒,你可以这样做:
// So we skip the `sleep` the first time
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
因为它在 async
函数中,await sleep(1000)
(注意:不是 delay
,你基于承诺的 sleep
) 屈服于浏览器,允许它进行任何绘图等。
这是一个简单的例子,只是在 drawChart
中添加一个 DOM 元素:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function example() {
const fplDeltas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
}
function drawChart(delta) {
const div = document.createElement("div");
div.textContent = delta;
document.body.appendChild(div);
}
(async () => {
try {
await example();
console.log("Done");
} catch (e) {
console.error("Error:", e);
}
})();
我很难使用 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
如果你想遍历 fplDeltas
并用每个增量调用 drawChart
,间隔一秒,你可以这样做:
// So we skip the `sleep` the first time
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
因为它在 async
函数中,await sleep(1000)
(注意:不是 delay
,你基于承诺的 sleep
) 屈服于浏览器,允许它进行任何绘图等。
这是一个简单的例子,只是在 drawChart
中添加一个 DOM 元素:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function example() {
const fplDeltas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
}
function drawChart(delta) {
const div = document.createElement("div");
div.textContent = delta;
document.body.appendChild(div);
}
(async () => {
try {
await example();
console.log("Done");
} catch (e) {
console.error("Error:", e);
}
})();