再帰関数に遅延処理を導入

同期処理をどこに入れるか

この記事は前回からの続きです。再帰関数factorialは1行で定義できます。同期を可能にするコードをこの関数に入れるのは難解です。幸い、同期をサポートする仕組みが仕様として確立されました。新設された仕様を応用した例を前回、掲載しました。

 

内容的には前回と同じですが説明を図にしました。再帰関数に遅延処理を加える方法の一つとして参考になりましたらありがたいです。

実行例

ブラウザの再ロードボタンを押して再実行できます。

 
 
 
 
 
 
 
 
 
 
 
 
 

 

サンプルコード

<html>
<Div style="float:left; width:216px; height:560px; font-size:22px; border:1px solid blue;">
<div id="fact01" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact02" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact03" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact04" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact05" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact06" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact07" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact08" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact09" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact10" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact11" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact12" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
<div id="fact13" style="width:210px; height:40px; margin-top:4px;">&nbsp;</div>
</Div>
<Div style="float:left; margin-left:34px"><img src="https://aidesign.lolipop.jp/wp-content/uploads/2022/03/myAsync.png" width=350" height="560"></Div>
<script type="text/javascript" charset="utf-8">
myAsync();							//main関数呼び出し

async function myAsync(){			//非同期関数を定義する際にasyncをつけて宣言する
  for(var i=1; i<=13; ++i){
	var id="fact"+("0"+i).slice(-2);
	var result = await myPromise(i);//実行結果を待つためにawaitをつけて実行
	document.getElementById(id).innerHTML += (" "+i).slice(-2)+"!= "+result;// 1 2 6 24 120 720
  }
}
function myPromise(num){			//非同期な処理をする核となる関数myPromise
	return new Promise(function(resolve) {
	  setTimeout(function(){resolve(factorial(num))},1000)//1秒のディレー後にresolve起動
	});
}
function factorial(n) {				//階乗を求めるrecursiveな関数
   return (n<=1) ? 1 : n * factorial(n - 1);
}
</script>
</html>

 

コメントを残す

下記項目は必須ですがメールアドレスは公開されません。名前はニックネームをお使いください。

CAPTCHA


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください