Javascript process freezes HTML input elements

1.7k views Asked by At

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.

3

There are 3 answers

0
Kira On BEST ANSWER

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 and setInterval. 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(Worker){
    //Browser supports worker
    //Your code
}
else{
    //Web worker is not supported in this browser
}

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.

0
Katana314 On

This doesn't surprise me. JavaScript runs on the UI thread. On each event handler or function, it is intended to quickly change any relevant DOM state information, start any asynchronous processes, and then finish as quickly as possible. Thus, nothing else can respond to any other events.

It sounds like your infinite process might work better either as a "Web Worker" (a slightly newer technology that allows for actual multithreading), or if it's checking the document's state constantly, perhaps schedule it on a repeated series of timeouts.

0
bjaksic On

Probably, because while js is running, the page is waiting on it to finish. You should execute it "asynchronously". Try to wrap it in setInterval like:

setInterval(function() {
    myFunction();    
}, 100);

function myFunction() {
  //Your code
}