I wonder about the origin of this variable

I found this example in a textbook.

My confusion lies in the origin of this interval variable. Where does it come from?

It's not defined within the data block, and you can't simply create a variable by assigning a value to it.

Could it possibly be a global variable in JavaScript?

const POMODORO_STATES = {
  WORK: 'work',
  REST: 'rest'
};
const STATES = {
  STARTED: 'started',
  STOPPED: 'stopped',
  PAUSED: 'paused'
};
const WORKING_TIME_LENGTH_IN_MINUTES = 1;
const RESTING_TIME_LENGTH_IN_MINUTES = 5;

new Vue({
  el: '#app',
  data: {
    state: STATES.STOPPED,
    minute: WORKING_TIME_LENGTH_IN_MINUTES,
    second: 0,
    pomodoroState: POMODORO_STATES.WORK,
    timestamp: 0
  },
  computed: {
    title: function () {
      return this.pomodoroState === POMODORO_STATES.WORK ? 'Work!' : 'Rest!'
    },
    min: function () {
      if (this.minute < 10) {
        return '0' + this.minute;
      }

      return this.minute;
    },
    sec: function () {
      if (this.second < 10) {
        return '0' + this.second;
      }

      return this.second;
    }
  },
  methods: {
    start: function () {
      this.state = STATES.STARTED;
      this._tick();
      this.interval = setInterval(this._tick, 1000);
    },
    pause: function () {
      this.state = STATES.PAUSED;
      clearInterval(this.interval);
    },
    stop: function () {
      this.state = STATES.STOPPED;
      clearInterval(this.interval);
      this.pomodoroState = POMODORO_STATES.WORK;
      this.minute = WORKING_TIME_LENGTH_IN_MINUTES;
      this.second = 0;
    },
    _tick: function () {
      //if second is not 0, just decrement second
      if (this.second !== 0) {
        this.second--;
        return;
      }
      //if second is 0 and minute is not 0, decrement minute and set second to 59
      if (this.minute !== 0) {
        this.minute--;
        this.second = 59;
        return;
      }
      //if second is 0 and minute is 0, toggle working/resting intervals
      this.pomodoroState = this.pomodoroState === POMODORO_STATES.WORK ? POMODORO_STATES.REST : POMODORO_STATES.WORK;
      if (this.pomodoroState === POMODORO_STATES.WORK) {
        this.minute = WORKING_TIME_LENGTH_IN_MINUTES;
      } else {
        this.minute = RESTING_TIME_LENGTH_IN_MINUTES;
      }
    }
  }
});
button:disabled i {
  color: gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app" class="container">
  <h2>
    <span>Pomodoro</span>
    <button :disabled="state==='started'" title="start" @click="start()">
      <i class="glyphicon glyphicon-play"></i>
    </button>
    <button :disabled="state!=='started'" title="pause" @click="pause()">
      <i class="glyphicon glyphicon-pause"></i>
    </button>
    <button :disabled="state!=='started' && state !== 'paused'" title="stop" @click="stop()">
      <i class="glyphicon glyphicon-stop"></i>
    </button>
  </h2>
  <h3>{{ title }}</h3>
  <div class="well">
    <div class="pomodoro-timer">
      <span>{{ min }}</span>:<span>{{ sec }}</span>
    </div>
  </div>
</div>

Answer №1

intervalvariable is established in the start function

this.interval = setInterval(this._tick, 1000)

in order to maintain a reference to setInterval for later clearing in the pause and stop functions. It may appear confusing that why interval is not defined within the state? The absence of its declaration in state does not prevent attachment to the Vue instance (this) through any method. This practice is permissible in JavaScript, independent from Vue.

Nevertheless, it would have been more advisable for the code's creator to declare interval in the state as interval: null, both to eliminate confusion and adhere to best coding practices.

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

Deactivating choices in Autoselect from Material UI

I am attempting to implement a feature in the autocomplete of material ui where options are disabled based on a specific condition. Each table row contains an autocomplete field, and when an option is selected in one row, it should be disabled in the next ...

Is there a way to remove a portion of a string?

Looking to remove a section of a string using JavaScript? I attempted var sentence = "C:\mnt\c\User\Foo\Bar"; var updatedSentence = sentence.replace("mnt\c", ""); But the result was not as expected ...

Discover how to efficiently load and display a JSON array or object using JavaScript

I am new to learning about json and d3, having just started a few hours ago. While I have basic knowledge of javascript, I need help with loading a json file and displaying all the arrays and objects on the console using d3. I tried to do it myself but unf ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

Creating a JQuery slider with customizable step sizes

Can the JQuery Slider (range slider / dual slider) be customized to handle non-linear values with inconsistent "step" sizes? I envision a horizontal Slider that looks like this: |----|----|----|----|----|--------|--------|-------------------------|------ ...

What is the best way to configure shared functions that can be used across all of my test suites when working with Protractor and Selenium?

Currently, I am actively developing an AngularJS protractor test suite. The configuration file for this project is structured in the following way: exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', baseUrl: 'http: ...

Straining data in text input fields using bootstrap

Looking for a way to filter data with bootstrap/jquery without using tables, just div rows and columns. Check out an example of how my form looks Here's a snippet of my code: <div class="row"> <div class="col-md-4"> <input class= ...

Determine the width of invisible images using JavaScript/jQuery

Please take a look at the jsFiddle Every time I run it, I am trying to retrieve the width of the images, but the values I get are as follows (check in the JS console) 400 0 575 533 0 ... Some values are zero, and I can't figure out why. It seem ...

Using Node.js, you can easily insert an EJS template file into a div element

I have a total of 2 ejs files that I am working with. I am trying to dynamically append a template based on the label that is clicked. First, here is the code from the index.ejs template: <!--- Header content-----> <div class="btn-group filter-s ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

Can a file be loaded using JS/HTML5 FileReader on a page that is not being served?

I am looking to create a simple game using HTML5/JS without requiring the user to run a webserver or connect to a website. I only want them to access an HTML page. However, it seems like FileReader can only be used with file type inputs. Is there a way f ...

Discover the secrets of accessing two distinct objects returned by a single REST URL with Backbone

I am working with a REST URL that looks like this: /users/<user_id>/entities This URL returns data containing 2 objects as follows: { "players": { "test_player2": { "_id": "test_player2", "user": "f07590 ...

Sharing information between routes in Vue.js

I've recently started working on a small project using vue.js. In my code, I have a client list in the file (index.vue), and I'm looking to pass the client ID to another file called (profile.vue). This is a snippet of my index.vue code: <rout ...

Is it feasible to restrict access to specific fields of an object in the Firebase database for viewing purposes using Firebase permissions?

Consider this JSON structure representing a Firebase DB: { "users": { "user0": { "name": "Mike", "age": 20, "relationship": "married", "friends": [...] }, "user1": { " ...

Guide to integrating a custom-designed email subscription form into a Node JS application

I've recently kicked off a project to build a basic web app using the following tools: Vue.js Carbon Design System My next objective is to integrate a mailing list. I aim to incorporate a simple form with two main components: a text box and a subscr ...

Issue with passing values from JavaScript to PHP not working as expected

For some reason, I just can't seem to get this line of code to work. It's like my brain is not cooperating: var all = color.val('all'); $('#cssColor" + <?php echo $page ?> + "', parent.document).attr("background-color", ...

JavaScript's GET method fails to retrieve the complete JSON file

I am facing an issue with a substantial JSON file that my JavaScript code is unable to pull in entirely. When I check the Network tab in Firefox developer tools, it shows that the data stops at around line 57,301 out of 528,342 lines in the JSON file. Ini ...