我有一個物件陣列,其中包含一個欄位,該欄位duration
指定Object
應該保持可見的持續時間。
每個Object
陣列都有自己的duration
.
所以我想在setTimout
.
像這樣的東西:(onClick)
const playScenes = () => {
const cpScenes = [...scenes];
for(let i; i < cpScenes.length;i ){
const timer = setTimeout(() => {
showScene(cpScenes[i]); //Show the current scene
}, cpScenes[i].duration); //Time changes automatically
}
clearTimeout(timer);
};
我考慮這個的方式是setTimeout
應該阻止for
回圈的執行,然后在指定的時間后運行,然后回圈繼續..
uj5u.com熱心網友回復:
setTimeout 和 setInterval 都不會阻止執行。相反,您可以做的是將它包裝成一個承諾,例如:
async function playscenes() {
const cpScenes = [...scenes];
for(let i; i < cpScenes.length;i ){
await (new Promise( (resolve) =>
const timer = setTimeout(() => {
showScene(cpScenes[i]);
clearTimeout(timer);
resolve();
}, cpScenes[i].duration);
})
}
基本上,對于每個回圈,程式將等待new Promise
解決,這在計時器用完時發生。如果您不了解異步代碼(async/await)并且 promise 有效,我強烈建議您先進行研究。盡管此代碼不應在 React 組件中運行,因為我假設您每次觸發 setTimeout 時都會更改狀態。你可以做的是:
imports ...
async function playscenes(showScene){...}
let scenesPlaying = false;
export function YourComponent(...){
...
if(!scenesPlaying) {
playscenes(showScene);
scenesPlaying = true;
}
...
}
uj5u.com熱心網友回復:
我真的不明白它與 有什么關系react
,無論如何,你可以使用recursion
而不是for-loop
讓它作業
function playScenes(scenes) {
if (scenes.length === 0) {
return;
}
const [scene, ...rest] = scenes;
setTimeout(() => {
showScene(scene);
playScenes(rest);
}, scene.duration);
}
uj5u.com熱心網友回復:
這是一個簡單for
的基于回圈的解決方案:
function newComputerMessage() {
let total = 0;
for (let i = 0; i < cpScenes.length; i ) {
total = cpScenes[i].duration;
setTimeout(() => showScene(cpScenes[i]), total);
}
}
如果您想查看作業,這里有一個帶有虛擬值的作業示例片段:
let cpScenes = [5000, 5000, 3000, 4000]
function test() {
let total = 0;
for (let i = 0; i < cpScenes.length; i ) {
total = cpScenes[i];
setTimeout(() => showScene('test'), total);
}
}
function showScene(num) {
console.log(num);
}
test()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470688.html
標籤:javascript 反应 for循环 设置超时