I have some buttons and input fields. One of the buttons enables a javascript process that is intented to run forever and cannot be terminated except by clicking the other button.
However, once the process is started, all the HTML elements are frozen, and therefore the process cannot be terminated.
I'm running in Opera if that is relevant.
The reason why all of your html element freezes because of the never ending code fired after button click. You should change the never ending code to be asynchronous so it will not affect the browser.
JavaScript does not support threading till HTML5, but code can be executed asynchronously using the methods
setTimeout
andsetInterval
. For your case, use setTimeout method.Refer setTimeout for more info about using it.
From HTML5, you can use web workers similar to threading. This concept is new so only limited support is available even in major browsers. Just type
"Html5 web worker"
in google you will get a lot of tutorial regarding this.Check this Link for browsers that support web workers
If you use
setTimeout
, I cannot guarantee that your browser will not hang because all the code are executed in the same thread. On the other hand, a web worker runs on a separate thread. Also, your javascript code should be present in a separate file if you use web worker.You can also check whether your browser supports web worker or not using the following code
If you chose to use web workers, start a worker during button click and make sure the worker is created only once. There are limitations like you cannot update DOM in a worker thread. If you need to break these limitations use
postMessage
method of the worker to communicate with the browser main thread.