Sagar Kodte
Sagar Kodte

Reputation: 3815

function inside a setTimeout gives undefined

I want to set some wait time after each api calling. So I have added setTimeout for api calling in for loop but it giving api service that is createAPIService undefined in setTimeout. Below is my code.

for (let i = 0; i < this.fooditemselecteddetails.length; i++) {
  this.spinnerService.hide();
  setTimeout(function() {
    this.common.createAPIService('api/booking/AddConcessions?CinemaId=' + this.cinemaid + '&TransactionId=' + this.temptransaction.TransactionId + '&ItemId=' + this.fooditemselecteddetails[i].id + '&Quantity=' + this.fooditemselecteddetails[i].quantity + "&BookingId=" + this.transactionAPIRequest.ORDER_ID, '')
  .subscribe((result: any) => {

      this.spinnerService.hide();
      this.addconcession = result;
      console.log(this.addconcession);


      if (this.addconcession.IsSuccess == true) {

        if (i == this.fooditemselecteddetails.length - 1) {
          localStorage.setItem("bookingid", this.transactionAPIRequest.ORDER_ID);
          this.common.createAPIService('api/booking/FinalBookingDetails?BookingId=' + this.transactionAPIRequest.ORDER_ID, '').subscribe((result2: any) => {
            this.vistavalidation = result2;
            if (this.vistavalidation.BookingID > 0) {
              this.common.createAPIService('api/booking/ContinueTransaction?CinemaId=' + this.cinemaid + '&TransactionId=' + this.temptransaction.TransactionId, '').subscribe((result3: any) => {
                if (result3.IsSuccess) {
                  this.ContinueTransactionresult = result3;
                  this.showTabOnClick('tabs-4');
                } else {
                  this.common.ShowNotification("Food Item", result3.Error, "info");
                  this.spinnerService.hide();
                }
              });
            } else {

              this.common.ShowNotification("Food Item", 'something went wrong, please try again', "info");
              this.spinnerService.hide();
            }
          });
        }
      } else {
        this.common.ShowNotification("Food Item", result.Error, "error");
        this.spinnerService.hide();

      }
    });
  }, 2000);

  console.log(this.addconcession);

}

Upvotes: 0

Views: 262

Answers (4)

Mike Devenney
Mike Devenney

Reputation: 1845

When you use the arrow function you create a closure. A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.

More detail here: http://javascriptissexy.com/understand-javascript-closures-with-ease/

Upvotes: 0

Nabil Shahid
Nabil Shahid

Reputation: 1458

Use arrow function i.e. setTimeout(()=>{ },1000). It will inherit the this of the parent and you would be able to access all methods and variables of class using this.

Upvotes: 1

Ajay Ojha
Ajay Ojha

Reputation: 390

replace this "setTimeout(function(){ " to "setTimeout(()=> { ".

Upvotes: 0

SiddAjmera
SiddAjmera

Reputation: 39432

Try using arrow function syntax to retain the scope of this

setTimeout(() => { instead of setTimeout(function() => {:

for (let i = 0; i < this.fooditemselecteddetails.length; i++) {
  this.spinnerService.hide();
  setTimeout(() => { ... }, 2000);

  console.log(this.addconcession);

}

Upvotes: 1

Related Questions