How to run javascript function in "background" / without interface freezing

I made an HTML form in which there are a lot of questions (coming from the database) on different tabs. The user then answers these questions. Every time the user changes the tab, my Javascript creates a save. The problem is that I have to iterate over all the questions every time the tab is changed, and it freezes the form for about 5 seconds every time.

I was looking for an answer on how I can run the save function in the background. There seems to be no real way to run something in the background, and many recommend using setTimeout(); For example, this How to get a group of js function running in the background

But none of these examples explains or takes into account that even if I use something like setTimeout(saveFunction, 2000); This does not solve my problem. In this case, he puts it off for 2 seconds.

Is there any way to solve this problem?

+4
source share
4 answers

There seems to be no real way to run something in the background ...

In most modern browsers (but not IE9 and earlier): Web Workers .

But I think that you are trying to solve the problem at the wrong level: 1. It should be possible to scroll through all your controls in the lot for less than five seconds and 2. There is no need to scroll through all the controls if only one of them has changed.

I suggest looking for these problems before trying to unload this treatment into the background.

For example, you might have an object that contains the current value of each element, and then the user interface for each element updates this object when the value changes. Then you will have all the values ​​in this object, without having to repeat all the controls.

+5
source

You can take a look at HTML5 web workers , but they are not all that widely supported.

+1
source

This library helped me a lot in a very similar problem that you describe: https://github.com/kmalakoff/background

This is basically a sequential background queue based on the WorkerQueue library.

0
source

Just create a hidden button. pass a function to its onclick event. Whenever you want to call this function (in the background), trigger a button click event.

 <html> <body> <button id="bgfoo" style="display:none;"></button> <script> function bgfoo() { var params = JSON.parse(event.target.innerHTML); } var params = {"params":"in JSON format"}; $("#bgfoo").html(JSON.stringify(params)); $("#bgfoo").click(bgfoo); $("#bgfoo").click(bgfoo); $("#bgfoo").click(bgfoo); </script> </body> </html> 
0
source

All Articles