Assuming that you want to stick with the original plan to insert text wherever the cursor happens to be, you would need something more deterministic than an arbitrary delay.
This script covers all the scenarios that I can think of:
tell application "System Events"
-- In case TextEdit was already running and all windows were closed
repeat until first window of application "TextEdit" exists
tell application "TextEdit" to make new document at the front
-- Ensure TextEdit can have focus
repeat until process "TextEdit" is frontmost
set frontmost of process "TextEdit" to true
-- Give focus to the window
set focused of first window of process "TextEdit" to true
keystroke "Hello world\n"
In particular, the scenarios I tested include:
- TextEdit was not running at all
- TextEdit was running, but had no document windows at all
- TextEdit was already running with one or more windows
To convince yourself that the technique is sound, try each of these scenarios with the loop bodies commented out, and you should see that the script will wait until the conditions are appropriate before continuing.
There is no guarantee, however, that the user won't deliberately try to induce a race condition while the keystrokes are being sent.