0

In my Javascript code I am trying to set up this code

    if(this.boolean == true) {
        setTimeout(function(){ this.boolean = false; }, 2000);

    }

But for some reason it won't work, the boolean just remains true. How can I fix this/what can I do instead? The setTimeout works with other lines of code but weirdly not this one.

5 Answers5

2

this behaves in a special way in JavaScript.

Change

setTimeout(function(){ this.boolean = false; }, 2000);

to

setTimeout(() => { this.boolean = false; }, 2000);

and the this keyword will be interpreted block-scoped.

messerbill
  • 4,582
  • 1
  • 19
  • 33
1

It's because of "this" - you can use a closure to do this:

var x = this;
var onTimeout = function(){
  x.boolean = false;
}

if(this.boolean == true) {
       setTimeout(onTimeout, 2000);
}

"this" is not what you think it is inside the setTimeout function:

setTimeout and "this" in JavaScript

If you have ES6 available, arrow functions use their lexical scope for this

var onTimeout = () => this.boolean = false; 
setTimeout(onTimeout , 2000);

More about that here:

https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e

mikeb
  • 8,943
  • 4
  • 43
  • 94
0

If you are not using arrow function, the this variable will be the one from setTimeout and not your main class because of its scope.

The following should resolve the issue.

    if(this.boolean == true) {
        setTimeout(() => { this.boolean = false; }, 2000);

    }
oktapodia
  • 1,494
  • 1
  • 13
  • 27
0

Functions have their own this, so this.boolean inside of function implies that you are trying to change the property boolean of the function itself. On the other hand, if you use arrow functions, you can avoid that because arrow functions don't have their own this.

setTimeout(() => { this.boolean = false }, 2000)
Mirakurun
  • 3,910
  • 4
  • 14
  • 31
0

The scope of "this" is changed in your function inside the setTimeout.

You could use the arrow function like other commenters have said.

Or, you can set a var as this, and then use that var in the functions inside the SetTimeout.

var coolThis = this;
if(coolThis.boolean == true) {
    setTimeout(function(){ coolThis.boolean = false; }, 2000);
}
Sudip Shrestha
  • 328
  • 2
  • 9