How to perform asynchronous functions in plugin

I want my plugin to display my UI first while I have an asynchronous function findAllElements running in the background like so:

I expected the synchronous parts of my code ie figma.showUI() to run first while findAllElements() is running in the background, but it seems like figma.showUI() is still waiting for findAllElements() to complete before the UI is displayed.

How do I use promises to get the behaviour I want? Also, would it be better to make use of custom events to load my background tasks instead?

Based on Figma’s documentation, it seems like my plugin code ie code.ts and ui.html are sharing the same main thread. Does this mean that when my UI basically freezes whenever my plugin is doing a task?

Not only your plugin UI, but the whole Figma UI.

This is a problem only for long-running complex tasks, e.g. traversing the Figma nodes tree.

As I’ve asked in another post, the code I’m executing are single and potentially expensive calls eg figma.root.findAll. Is there a way to pause or break up these function calls with a delay eg for every 100 nodes returned by findAll(), pause FindAll() and process the 100 nodes that we got before resuming FindAll()?