Make long-running processes non-blocking

A program that takes a long time to execute might freeze the browser and cause messages to appear in the window, saying that the script takes a long time to run and asking the user if he wants to stop it or continue.

In this page, the process consists in building a 1,000,000 element list. Running it without any precaution causes the browser to freeze.

To avoid this and keep the page responsive, we use the function set_timeout() defined in module browser.timer . The program defines a function add_rows() that only adds 5,000 elements (we are sure it will not block the browser), and ends with this line:

timer.set_timeout(add_rows, 0)

This instruction tells the program to run the function again in 0 seconds, ie almost immediately, but just before it gives control back to the browser, which can for instance print something on the page or react to a click on a button.

Although it lasts much longer than the time after which a browser prints a warning, the script remains responsive, for instance you can enter text in the textarea and click on the button to know the text lengths (the browser will of course react a little slower than if no heavy computation was done in the same time).