How to make a group of js functions run in the background

self.showPanel(); self.updateSliderValue(); self.addPoints(1,2,3); self.setOptions(); self.removeValues(); 

addPoints method adds points to the application, and it takes a lot of time, so I want it to work in the background, and the application switches to setOptions and other functions under it. Please, help.

+2
source share
2 answers

javascript is a single thread application, which means there is nothing like a background thread to run.

What you can do is run the addPoints function after the completion of the main function, you can use setTimeout to do this

 setTimeout(function(){ self.addPoints(1,2,3); }, 0) 

This will delay the execution of addPoints until the current execution of the script is completed.

+7
source

The browser has some options (provided that the client side is associated with the jquery tag)

First, you can use setImmediate:

https://developer.mozilla.org/en-US/docs/Web/API/window.setImmediate

Secondly, you can use timers and split it, a very simplified example, and then if you want to process more things, just insert them into the subject material from time to time. Any of several permutations on this.

  int howoftentocheck = 60*1000; //60s var thingstodoarray = []; thingstodoarray.push("do this"); function checkForStuffToDo(){ if(thingstodoarray.length){ //.. do things be sure and pop or shift the thing you did. }else{ setTimeout(function() { checkForStuffToDo() }, howoftentocheck) } }(); 

Thirdly, you can use events instead of polling, so register events using, say, jQuery or another library that offers events, then you can fire them when you want to do some processing using .on and .trigger, for example.

http://api.jquery.com/trigger/

I am sure there are several other options, but the goal is to keep the event loop tight so that you are not distracted from the user experience, etc.

+2
source

All Articles