setTimeout does not include the function showBox

Whenever I use console.log(this.showBox) inside the setTimeout() function, it unexpectedly returns undefined instead of false. Could someone please explain if the setTimeout() affects the accessibility of this.keyword? Thank you!

<script>
import Block from "./components/Block.vue"
export default {
  name: 'App',
  components: {
    Block,
  },
  data() {
    return {
      isPlaying: false,
      delay: null,
      timer: null,
      reactionTime: 0,
      showBox:false,

    }
  },
  methods: {
    startGame() {
      this.isPlaying = true;
      //this.delay = 2000 + Math.floor(Math.random(1,4000) * 4000)
      this.delay = 1000
      console.log(this.delay)
      console.log(this.showBox)

      setTimeout(function() {
        console.log(this.showBox)
      }, this.delay);
    },
  },
}
</script>

Answer №1

Despite the existence of a definitive answer, I feel compelled to jot down my own thoughts on the matter. It is worth noting that setTimeout & setInterval each establish their own context, rendering the variable this unachievable within those contexts.

Answer №2

Using arrow function is effective, but there are alternative methods you can explore to solve this issue. Consider looking into the call, bind and apply techniques.

To tackle your problem, utilizing the bind method is one approach.
Keep in mind that bind creates a new function and establishes this as the specified value. Check out: MDN bind() method documentation for more details.

setTimeout(function() {
   console.log(this.showBox)
}.bind(this), this.delay);

Answer №3

If you utilize this code within a setTimeout function, it will establish its own unique context leading to undefined results. To maintain the same context, consider using an arrow function.

setTimeout(() => {
        console.log(this.showBox)
      }, this.delay);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Collapse the accordion by sliding it back to the top position

I have successfully implemented the Flexible Slide-to-top Accordion on my webpage. Initially, I struggled with the functionality to have only one accordion open at a time due to my limited knowledge of jQuery. However, after overcoming this challenge, I n ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

What causes HTML validator errors in all head meta-tags?

After running my HTML through a validator, I was shocked to discover around 80 errors even though the site appeared to be functioning properly. Here is an excerpt of the code: <!DOCTYPE html> <html lang="da-DK"> <head> <meta charset=" ...

Creating a dynamic webpage using the MVC design pattern within a Docker container

I am facing a challenge with my dotnet core application that has authorization. Due to company policy restrictions, Bearer tokens cannot be stored on the front-end. To work around this, I want to utilize an MVC Controller. However, the application is built ...

Change the background color of a table cell based on its value with the help of JavaScript

I am attempting to apply color to cells in an HTML table (generated automatically by Python and Django) based on the content of the cells. Below is my table. I want to specifically color the column "status". Whenever the word "Cloture" appears, I would li ...

What could be causing my webpage to freeze every time a filter button is selected?

Tasked with developing a webpage similar to Pinterest by utilizing data from a JSON response. Each JSON object contains a service_name key, which can be manual, twitter, or instagram. I made an effort to implement three filter buttons to only display the r ...

Tips for postponing 'not found' error until the data has finished loading in Vue.js

I am accessing the following route: http://site.dev/person/1 The structure of my component is as follows: // PeopleComponent.vue <template> <div> <template v-if="person == null"> <b>Error, person does not exist.</b& ...

What is the best approach to creating a Typescript library that offers maximal compatibility for a wide range

My Vision I am aiming to develop a versatile library that can cater to both JavaScript and TypeScript developers for frontend applications, excluding Node.js. This means allowing JavaScript developers to utilize the library as inline script using <scri ...

Constructing Jquery object with added event listener

Take a look at the code I've provided below: <body> <canvas id="canvas" height="300" width="300" style="border:1px solid" /> </body> <script> function maze(canvas){ this.ctx = canvas[0].getContext("2d"); ...

Maintain the fixed placement of an absolute element by adjusting the browser window size

Seeking assistance here - I currently have a box that occupies the entire window. This box is designed to be responsive with a noticeable red border. Within this box, my goal is to insert tables with specific X and Y coordinates. However, my issue arises ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

jQuery's query yields a NULL result

y.html: <h4> Modified: <span id="link-modified"></span></h4> --> Date is not displayed jQuery: var modified_date = new Date((data.modified)*1000); --> data.modified is in UNIX timestamp $('#link-modified').text(mo ...

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an & ...

"Utilizing the connect() and withStyles() methods in React for class components: A step-by-step guide

Looking for ways to utilize connect() and withStyles() in React for a class component? const customStyles = makeStyles(theme => ({...}); const stylesObject = customStyles(); class CustomComponent extends React.Component { ... render() { ...

Vue.js/Vuetify - Dynamically filter select options based on another select value

Is there a way to filter data in order to populate one select based on the selection made in another select? For example, if I choose a state from one select, can I have a second select loaded with all cities from that specific state? I am using vue.js and ...

What is the best way to prevent the background-image fade effect in Chrome?

While transitioning the background-image, I noticed a difference between Chrome and Firefox. Firefox simply replaces the image instantly as expected, while Chrome adds a fade effect to the transition. Although this may be visually appealing, it introduces ...

Comparing the Calculation of CSS Selector Specificity: Class versus Elements [archived]

Closed. This question requires additional information for debugging purposes. It is not currently accepting answers. ...

The sum is being treated as a concatenation instead of an addition in this case

Why is the somma value showing the concatenation of totaleEnergetico and totaleStrutturale instead of a sum? RiepilogoCombinatoStComponent.ts export class RiepilogoCombinatoStComponent implements OnInit { constructor() { } interventi: AssociazioneI ...

Use jQuery to extract data from the URL instead of relying on PHP

http://h3gsat.altervista.org/DettagliCompleto.php?id=4567 I attempted to extract the id parameter without success. I am attempting to accomplish this using JavaScript (jQuery) instead of PHP, but I am unsure of how to proceed. ...