They don't detect when JavaScript execution is finished. The halting problem means that it is impossible to know if arbitrary code that you are running will finish or not. The best you can do is run it for a certain amount of time see if it finishes by then.
So that is exactly what Google does, it runs the code in the page for five seconds, and then it takes a snapshot of the document object model for indexing. It doesn't matter if the JavaScript is finished by then or not, you get only five seconds. If you want your page content and meta description included in the search index, you need to make sure that fetching the data from your server and running the JavaScript to insert it in the DOM consistently takes less than 5 seconds from anywhere in the world.
Most JavaScript framework offer server-side-rendering (SSR) that you should be using to sidestep this problem. SSR allows you to run the JavaScript to render the initial page on the server, usually using NodeJS. Then clients get normal HTML. That is typically faster for users (better UX) and easier for search engines to index.