8

I am getting 'Restricted async operation 'setTimeOut' in LWC' error in VS Code when I use setTimeOut in connectedCallback.

.html file

<template>
<div class="wrapper">
<header class="header" if:true={ready} >Available Bikes for {name}</header>
</div>
</template>

.js file

import { LightningElement, track, wire } from 'lwc';

export default class Selector extends LightningElement {
@track
ready = false;
connectedCallback() {
   setTimeout(() => {
       this.ready = true;
   }, 3000);
} 

What is the alternative to perform any action after certain time in LWC?

2
  • The linter flags async patterns because overuse leads to code that is difficult to maintain and there is almost always a better way to do it. Would you mind sharing what you are trying to do? May 30, 2019 at 5:19
  • I was basically experimenting with connectedCallback() and came to this error and could not find the exact reason behind this. I think I was trying display some content once the page loads which can be achieved with renederedCallback()
    – devforce
    May 30, 2019 at 7:51

1 Answer 1

10

Settimeout is generally restricted for LWC as there are other ways to implement the functionality. More information here

If you still need to use you can disable es-linting by adding the below before your settimeout line

// eslint-disable-next-line @lwc/lwc/no-async-operation

renderedCallback() {
   if(!this.ready)
   this.ready == true;
} 

From documentation

Due to mutations, a component is usually rendered many times during its lifespan in an application. To you use this hook to perform a one-time operation, use a private boolean property like hasRendered to track whether renderedCallback() has been executed. The first time renderedCallback() executes, perform the one-time operation and set hasRendered = true. If hasRendered = true, don’t perform the operation.

5
  • I tried with renderedCallback and ready gets set to true once page gets rendered which is fine. However, on inspect I found that renderedCallback is getting called multiple times (in this case 3 times).
    – devforce
    May 7, 2019 at 10:30
  • so stop it by checking if ready is true dont set it again. This has been called out in the documentation as well. have updated my answer to reflect that
    – RedDevil
    May 7, 2019 at 10:44
  • got it ! Thanks!
    – devforce
    May 7, 2019 at 10:54
  • what if there is legit reason for a fix wait , the hook would work then would it, also when I tried to ignore the lint using the comment you suggested I get: Inline rule disablement not allowed. Nov 7, 2022 at 7:23
  • Currently, this seems to be triggering a false positive in Salesforce Scanner : github.com/forcedotcom/sfdx-scanner/issues/1161
    – altius_rup
    Aug 28, 2023 at 14:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .