2017-05-03 16 views
0

timeout()が呼び出されると、終了するのに100 * 100msかかる。関数呼び出しが終了するまで実行を待つ

doThousandTimes()が呼び出されると、終了するには1000 * 100 * 100ミリ秒を要してください(SHOULD)。ただし、前の呼び出しが終了する前にtimeout()が呼び出されます。私は遅く、これに対する解決策を見つけることに失敗しています。私はどんな助けにも感謝しています。時間指定コールバックのそのシリーズを完了するためにtimeoutのためのあなたのdoThousandTimes待機中

var count = 0; // variables to hold random value and displacement 
 
var i; 
 
function stuff() { 
 
    console.log("stuff"); 
 
} 
 

 
function doThousandTimes() { //executes 1000 times 
 
    while (count < 1000) { 
 
    i = 0; 
 
    timeout(); 
 
    count++; 
 
    } 
 
} 
 

 
function timeout() { //executes 100 times 
 
    setTimeout(function() { 
 
    stuff(); 
 
    if (i < 100) { 
 
     i++; 
 
     timeout(); 
 
    } 
 
    }, 100); 
 
} 
 
console.time("do1000"); 
 
doThousandTimes(); 
 
console.timeEnd("do1000"); 
 
console.time("timeout"); 
 
timeout(); 
 
console.timeEnd("timeout");

答えて

1

何もありません。

var count = 0; 
 
var i; 
 
function stuff() { 
 
    console.log("stuff: ", count, i); 
 
} 
 

 
function doThousandTimes(done) { 
 
    if (count < 20) { 
 
    // Update and call timeout, passing in a function 
 
    // to use as its done callback that will 
 
    // call doThousandTimes again 
 
    count++; 
 
    i = 0; 
 
    // `bind` creates a function that will get done as an argument 
 
    timeout(function() { 
 
     doThousandTimes(done); 
 
    }); 
 
    } else { 
 
    // We're done -- call our done callback if any 
 
    if (done) { 
 
     done(); 
 
    } 
 
    } 
 
} 
 

 
function timeout(done) { 
 
    setTimeout(function() { 
 
    stuff(); 
 
    if (i < 10) { 
 
     i++; 
 
     timeout(done); 
 
    } else { 
 
     // Done -- call our "done" callback, if any 
 
     if (done) { 
 
     done(); 
 
     } 
 
    } 
 
    }, 100); 
 
} 
 
// Note putting the `timeEnd`s and such *into* callbacks below 
 
console.time("do1000"); 
 
doThousandTimes(function() { 
 
    console.timeEnd("do1000"); 
 
    console.time("timeout"); 
 
    timeout(function() { 
 
    console.timeEnd("timeout"); 
 
    }); 
 
});
.as-console-wrapper { 
 
    max-height: 100% !important; 
 
}

注:私が変わってきたあなたはコメントを参照してください、そうdoThousandTimesは、次を続行することができ、それはそのシリーズで行うのときに呼び出すことtimeoutにコールバックを渡すことができます(count < 1000ではなく)count < 20とではなくi < 10に制限されているため、スニペットを実行して完了することができます。また、stuffを最新のcountiに更新しました。

+0

@mplungjan:ありがとうございました。最後に 'timeout'コールなどが欠落しました。一定。 –

関連する問題