admin管理员组

文章数量:1327937

self.showPanel();
self.updateSliderValue();

self.addPoints(1,2,3);

self.setOptions();
self.removeValues();

addPoints method adds points to app and it takes quite lot of time, so I want it running in background and the app goes to setOptions and other functions below it. Please help.

self.showPanel();
self.updateSliderValue();

self.addPoints(1,2,3);

self.setOptions();
self.removeValues();

addPoints method adds points to app and it takes quite lot of time, so I want it running in background and the app goes to setOptions and other functions below it. Please help.

Share Improve this question asked Jun 20, 2013 at 3:40 H VH V 1312 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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

What you can do is run the function addPoints after the main function is pleted, you can use setTimeout to do that

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

This will defer the execution of addPoints till the current script executions are over.

Browser side you have some options (assuming client-side due to the jquery tag there)

First, You might be able to take advantage of setImmediate:

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

Second, you can use timers and split it up, a very simplistic example, then if you want to process more things, just stuff them into the thingstodoarray every now and then. Any one of a number of permuations 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)
       }
    }();

Third, instead of polling you can use events, so register events, say with jQuery or some other library that offers events, then you can fire them when you would like to do some processing, using .on and .trigger for example.

http://api.jquery./trigger/

I'm sure there are several other options, but the goal is to keep your event loop tight so that you don't take away from the user experience, etc.

本文标签: javascriptHow to get a group of js function running in backgroundStack Overflow