3

I am performing a javascript sorting an array of objects of size 2500 records that is displayed in lightning data table. This takes 3-5 seconds. Meanwhile I wanted to show lightning-spinner.

Html Code

<template if:true={showSpinner}>
                <lightning-spinner alternative-text="Loading" size="medium" ></lightning-spinner>
            </template>

Javascript code

this.showSpinner=true;
this.allData =  this.sortMyData(this.allData,sortByMapped,this.sortDirection);
this.showSpinner=false;

Spinner never displays. But If I put a breakpoint in the second line , the spinner appears. I believe this happens because the time to sort is very less. But the time taken to render the records in data table takes more time. If this is correct , is there a way I can show the spinner till the complete table renders the data ? If not, what am I missing?

1 Answer 1

11

The problem is that the browser can't update the view while JavaScript is running. In order to make this work the way you expect, you need a brief pause:

this.showSpinner = true;
new Promise(
  (resolve,reject) => {
    setTimeout(()=> {
        this.sortMyData(this.allData, this.sortByMapped, this.sortDirection);
        resolve();
    }, 0);
}).then(
    () => this.showSpinner = false
);

Here's a simulation of that in action.

3
  • It worked great as I expect now :) . Thank you ! One question though, you mentioned a brief pause, but zero is being passed to setTimeout method, which means the code executes immediatly correct ? Then how there is a brief pause? Dec 3, 2019 at 12:35
  • 1
    @RajaVivekanandhan Zero simply means "as soon as possible after the current execution context". Most browsers consider it to be at least 4ms. Regardless, it gives the browser enough time to update the view before running your sort method, because browsers refresh the view every time there's any break in JavaScript execution.
    – sfdcfox
    Dec 3, 2019 at 14:52
  • Thanks for the explanation @sfdcfox Dec 3, 2019 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.