executing a "background process" in javascript

Can JavaScript execute functions in the background?

I am using the pdfmake tool to generate a PDF within an AngularJS application, but the generation process takes around 3-4 seconds and causes the UI to freeze completely.

I want to run a background task to initiate the PDF download without impacting the user interface. Is this achievable?

This is how I currently implement pdfmake (with custom factories named pdfmake and _):

'use strict';

angular.module('App')

    .service('CatalogPdfService', ['pdfmake', '_', '$q', '$filter',
        function (pdfmake, _, $q, $filter) {

            var $translate = $filter('translate');
            var listDate = new Date();

            return {
                download: download
            };

            function download(data) {

                listDate = _.first(data).publishedOn;
                console.log('initiating download process');
                var deferred = $q.defer();
                var filename = $translate('APP.EXPORT.pdf.catalog.title', {date: $filter('amDateFormat')(listDate, 'DDMMYYYY')}) + '.pdf';
                create(data).download(filename, function () {
                    console.log('download completed');
                    deferred.resolve();
                });
                return deferred.promise;
            }

            // Other code implementation remains unchanged...

        }]);

Answer №1

If you're looking to generate a PDF using a Web Worker, there are some restrictions to be mindful of. Check out this reference for more information.

One approach is creating an Angular factory for running tasks on a worker thread. Here's an example:

/*
Here's an example on how to get this sack of moldering spuds to do something:

 var myWorker = new MyWorker({ fn: function() {
    this.onmessage = function(args) {
        setTimeout(function() {
            this.postMessage('Got args: ' + args.data);
        }, 20000);
    };
 } });

 myWorker.do('Test').then(function(message) {
    alert(message);
 });
 */

'use strict';

angular.module('myApp')
    .factory('MyWorker', function($q) {
        var _worker;

        var MyWorker = function(settings) {
            _init(settings);
        };

        MyWorker.prototype.do = function(args) {
            var deferred = $q.defer();

            _worker.onmessage = function(message) {
                deferred.resolve(message.data);
            };

            //Fire up the blades.
            if (args)
                _worker.postMessage(args);
            else
                _worker.postMessage();

            return deferred.promise;
        };

        MyWorker.prototype.destroy = function() {
            _worker.terminate();
        };

        function _init(settings) {
            if (settings.script)
                _worker = new Worker(settings.script);
            //Need to make this IE (10+) friendly.
            else if (settings.fn) {
                var blobUrl = window.URL.createObjectURL(new Blob(
                    ['(', settings.fn.toString(), ')()'],
                    { type: 'application/javascript' }
                ));

                _worker = new Worker(blobUrl);
            }
        };

        return MyWorker;
    });

This showcases one way it can be implemented in AngularJS, but keep in mind that adjustments may be needed based on your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while adding a value from MongoDB to a list

Encountering an issue when attempting to add an element to an array using a for loop MY CODE router.get('/cart', verifyLogin, async (req, res) => { var products = await userHelpers.getCartProducts(req.session.user._id) console.lo ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

Three Divs stacked on top of each other, with varying heights based on

I am seeking a solution for creating a layout with three vertically stacked divs. The top div must have a fixed height of 60px. The middle div might contain content exceeding its height, therefore we've set it to overflow: auto. But regardless of th ...

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

One way to retrieve this attribute with jQuery is by specifying the div element in question

I am facing an issue with a div that is defined within a particular context. Let's consider the div as shown in the code snippet below: <td itemid='desired number'> <div>div 1</div> <div class="action">div 2</ ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

Customized coordinates on leaflet map fail to render

Utilizing the Where the ISS at API to retrieve the current latitude and longitude coordinates of the ISS involves making a serverside request structured like this: app.get("/coordinates", async (req,res) =>{ try{ const result = await axios.get(A ...

Leveraging Cheerio in Node.js to locate a precise value within an option tag

I'm facing difficulties in selecting the exact number (in this case 7) which is the value of the option. This is what I'm attempting: var $ = cheerio.load(html); console.log($('ProductSelect').val($("option:contains('7')").v ...

Click event inside a repeat loop

Working with AngularJS, I have a collection of colors that each have a specific title and type. These colors are displayed in a list format on the webpage. Now, I am looking to enhance this by incorporating a menu option that allows users to filter and vi ...

Leveraging JavaScript Functionality with ASP.NET Identity Roles

I'm currently working on an application that utilizes JQuery DataTables. The goal is to have these tables visible to all users, but restrict the click functionality to a specific user role. One way I can achieve this is by setting up authorization on ...

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

Is there a way to incorporate a method into a JavaScript object dynamically without encountering any unusual errors?

I am dealing with an array of JavaScript objects that I need to modify. Here is an example of the initial setup: let headers = [ { text: 'something', value: 'something else' }, { text: 'something1', value ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

Steps to design a unique input radio button with embedded attributes

In my current project, I am utilizing react styled components for styling. One issue that I have encountered is with the text placement within a box and the need to style it differently when checked. What have I attempted so far? I created an outer div a ...

The asynchronous function is not being executed by onSubmit

I am attempting to create a function that will generate a gif when the "get gif" button is pressed. However, I am facing an issue where nothing shows up in the console and the page reloads. 1) The requirement is for the client to enter a value 2) Set th ...

Can you explain the concept behind the event processing loop in Node.js?

Currently, I am reviewing a gist that outlines a file walk algorithm in JavaScript // ES6 version using asynchronous iterators, compatible with node v10.0+ const fs = require("fs"); const path = require("path"); async function* walk(d ...

Adjust the dimensions of the initial cell

I need to adjust the size of the initial "generated" cell in a grid. The grid is not present in the HTML markup until JavaScript prints RSS information on it, making it difficult to target specific rows or cells directly. Note: The first element is hidden ...

Display numerical data at precise locations above an image

Currently, I am working on a project where I am adding multiple marker pins to an image and saving their positions (x and y coordinates) to a database for later use. To see the code I have written so far, you can visit this link: https://jsfiddle.net/at3w ...

Is it feasible to commit an object on Vue X through Actions?

I have a question regarding Vue X and actions (with commit). Can an object be passed as input in Commit? Similar to: ... action{ ResetLoginStats({commit}){ commit({ 'SetMutation1':false, 'SetMutation2':true, &a ...