You can create these threads inside functions just fine I’m not quite sure what you are thinking about for your potential code’s layout when you say ‘do this from a function’ though.
(Also, formatting is achieved by placing a blank line before and after your code snippet, and on these lines, placing three backticks each: ```)