What is the meaning of [And thereby hangs a tale]

From Shakespeare’s As You Like It, 1600.

JAQUES:
A fool, a fool! I met a fool i’ the forest,
A motley fool; a miserable world!
As I do live by food, I met a fool
Who laid him down and bask’d him in the sun,
And rail’d on Lady Fortune in good terms,
In good set terms and yet a motley fool.
‘Good morrow, fool,’ quoth I. ‘No, sir,’ quoth he,
‘Call me not fool till heaven hath sent me fortune:’
And then he drew a dial from his poke,
And, looking on it with lack-lustre eye,
Says very wisely, ‘It is ten o’clock:
Thus we may see,’ quoth he, ‘how the world wags:
‘Tis but an hour ago since it was nine,
And after one hour more ’twill be eleven;
And so, from hour to hour, we ripe and ripe,
And then, from hour to hour, we rot and rot;
And thereby hangs a tale.’ When I did hear
The motley fool thus moral on the time,
My lungs began to crow like chanticleer,
That fools should be so deep-contemplative,
And I did laugh sans intermission
An hour by his dial. O noble fool!
A worthy fool! Motley’s the only wear.