繁体   English   中英

等待执行,直到函数调用结束

[英]Wait to execute until a function call comes to an end

调用timeout()时,需要100 * 100毫秒才能完成。 (成功。无需修复。)

调用doThousandTimes()时,应花费1000 * 100 * 100毫秒来完成。 但是,在上一次调用完成之前将调用timeout()。 我很慢,一直未能找到解决方案。 我将不胜感激。

 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"); 

doThousandTimes没有任何doThousandTimes等待timeout完成其一系列定时回调。 您可以将回调传递给timeout ,在完成其系列时将调用该timeout ,因此doThousandTimes可以继续执行下一个,请参见注释:

 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; } 

注意:我已将限制更改为count < 20 (而不是count < 1000 )和i < 10 (而不是i < 100 ),只是为了使摘要可以运行完整。 我还更新了stuff以显示当前counti

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM