-
Notifications
You must be signed in to change notification settings - Fork 4
Workers
Starting at version 1.20, OGX.JS supports live
WebWorkers
. They can be used to run code in the background, declared in the foreground (with limitations). Functions are supported, but object/class methods are not.
All paths are relative to root. The function's scope is locked to itself. This feature is experimental.
OGX.Workers.add(_FUNCTION_, _OPTIONAL_ID_, _OPTIONAL_SCRIPTS_);
OGX.Workers.remove(_ID_);
OGX.Workers.call(_ID_, _FNC_PARAMS_, _OPTIONAL_CALLBACK_, _OPTIONAL_PARAMS_);
OGX.Workers.run(_FUNCTION_, _ID_, _OPTIONAL_SCRIPTS_, _INTERVAL_, INTERVAL_PARAMS_, _OPTIONAL_CALLBACK_, _OPTIONAL_PARAMS_);
OGX.Workers.start(_ID_);
OGX.Workers.stop(_ID_);
const my_function = function(object){
//object is _FNC_PARAMS_
//your slow code here that you want to run in the background instead
return something;
};
const worker_id = OGX.Workers.add(my_function);
You can also specify a unique id when creating a worker
OGX.Workers.add(function(object){...}, 'my_id');
You can also use non anonymous functions
function myFunction(object){ ... }
OGX.Workers.add(myFunction, 'my_id');
You can also reference some files or scripts in your worker (array of file-path expected)
OGX.Workers.add(myFunction, 'my_id', ['myfile.js']);
And you can also call a main file instead
OGX.Workers.add('my_script.js', 'my_id');
Note that in that case, your worker file should handle the parameters and sources on its own.
A complete practical example of using OGX.List and Moment in a worker
OGX.Workers.add(function(__list){
const d = moment();
const list = new OGX.List(__list);
return d.format('YYYY-MM-DD')+' '+list.length;
}, 'test', ['js/lib/moment/moment.min.js', 'js/lib/globules/ogx.list.min.js']);
OGX.Workers.call('test', [{a:0}, {a:1}], function(res){console.log(res)});
Depending on your function, you can pass parameters when calling a worker
OGX.Workers.call(worker_id, 'whatever', function(result){
//do whatever with result
});
Note that
optional_data
is only useful when using non anonymous functions
optional_data
is the optional parameter_OPTIONAL_PARAMS_
when calling the worker
You can also declare a Worker and run it every x ms. Here we run a function in the background every second
OGX.Workers.run(myFunction, 'whatever', null, 1000);
Note that you don't need to use
add
if you userun
. Also note that, even if the tab is blurred, the worker will still run in the background and the front-end callback will be executed.
Then you can start or stop the interval as you need. Note that it is automatically started upon using
run
.
OGX.Workers.stop('whatever');
OGX.Workers.start('whatever');
OGX.Workers.remove(worker_id);
- Welcome
- Changelog
- Structure
- Configuration
- Getting started
- CLI
- Poly
- Core
- Templating
- Routing
- Controllers
- Components
- Extra Components
- Helpers
- Styling
- Debugging