dispatchEvent
sends the event synchronously to the target, so when you use dispatchEvent
the event handler frames accumulate on the stack and eventually overflow.
If you want to simply "loop forever" you have a few choices. Which choice is correct depends on how you want your code to interact with other events. I notice that your code suggests that it will updateUI()
. Well, your event handler needs to return to the browser's event loop periodically so that it can paint your updated UI. Using setTimeout(loop, 0);
is a good way to achieve this:
function loop() {
doSomeWork();
updateUI();
setTimeout(loop, 0);
}
loop(); // get things started
The call to setTimeout
will return before loop
is invoked again; then the browser will invoke loop
again. In between calls to loop
the browser may run other code, such as painting the changes in the UI, or invoking other event handlers in response to clicks and other events.
If you want you can make your loop run more slowly by increasing the delay from 0 msec to something larger. This might be useful if your loop is doing animation.
If you want your loop to stop, then don't call setTimeout
and it won't be called again.
Now here is an alternative technique:
If you are using a relatively recent version of Firefox, Chrome or Safari you can use a new feature called workers to run your loop. Workers have their own event loop, so it is OK to write code like this:
// worker code
while (true) {
doSomeWork();
// post messages to update the UI
}
Workers run separately from other scripts; to push results into the page itself you need to use a function called postMessage
. Here is the relevant spec, however you might want to also search for tutorials or post a follow-up question because working off the spec can be difficult at first.