Is it full script? What is the purpose of the `toggle` variable?
But I see a possible problem with this code. It sends Space key too frequently. Likely the active app is too slow to process it. Then OS buffers many key events and sends them to the app even (possibly long) after the script ended. There is no way to know whether the target app processed sent keys. Try to make slower. For example
But I see a possible problem with this code. It sends Space key too frequently. Likely the active app is too slow to process it. Then OS buffers many key events and sends them to the app even (possibly long) after the script ended. There is no way to know whether the target app processed sent keys. Try to make slower. For example
keys.send("Space"); 100.ms();.

Having problems with quickly closing a macro