-2

I would like convert JavaScript code on objective code. I don't know where is my problem, but maybe it is setTimeout?

When I use first normal code, my loading bar width are longer about 10 percent every 350 miliseconds. (10 times, and website go to subpage ).

But when I use my second objective code. Loading bar width not growing. Maybe problem is in setTimeout?

//THIS WORKS

function loading_text()
{
document.getElementById("text_ladowanie").style.visibility="visible";
document.getElementById("ladowanie").style.visibility="visible";
}

var i = 10, howManyTimes = 110,counter=0;

function loading_screen() {
   document.getElementById("ladowanie_postep").style.width=i+"%";
    i=i+10;
    if( i < howManyTimes ){
        setTimeout( loading_screen, 350 );
    }
    counter++;
    if(counter>=10)
    {
        window.location="program.php";
    }

}

//THIS NOT

var start_screen = {                    
i: 10,
howManyTimes: 110,                      
counter:0,
loading_text: function()
{
document.getElementById("text_ladowanie").style.visibility="visible";
document.getElementById("ladowanie").style.visibility="visible";
},
loading_screen: function() {

    document.getElementById("ladowanie_postep").style.width=this.i+"%";
    this.i=this.i+10;
    if( this.i < this.howManyTimes){
        setTimeout( start_screen.loading_screen, 350 );
    }
    this.counter++;
    if(this.counter>=10)
    {
       window.location="program.php";
    }

}

};
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
k0fik0
  • 7

1 Answers1

0

The problem is with the callback function of the settimeout. You can try this use arrow function where this is determined by surrounding scope.

var start_screen = {
  i: 10,
  howManyTimes: 40,
  counter: 0,
  loading_text: function() {
    console.log('loading_text called')
  },
  loading_screen: function() {
    //document.getElementById("ladowanie_postep").style.width=this.i+"%";
    this.i = this.i + 10;
    if (this.i < this.howManyTimes) {
      setTimeout(() => {
        console.log('loading_screen called')
        this.loading_screen();
      }, 350);
    }
    this.counter++;
    if (this.counter >= 10) {
      console.log('navigate to program.php')
      //window.location="program.php";
    }
  }

};
start_screen.loading_screen()
brk
  • 48,835
  • 10
  • 56
  • 78