There are a couple of issues here: specifically, the `this.myMethod` function is not recognized as a function, and the click event added by the `addEventListener` function

I am currently attempting to create a timer using vue.js, but I am encountering some issues with my methods section:

methods: {         
    saveRunningMethod() {
        var runningData = {
            duration: `${this.hour} : ${this.minute} : ${this.second}`,
            username: this.$store.state.user.username
        }
        this.$store.dispatch('saveRunning' , runningData)
        console.log(runningData);
    },
    startTimer(){     
        this.isTimerStart = true;
        var timer = window.setInterval(() => {

           var e = document.getElementById("stopBtn")
           e.addEventListener("click", function(){ 
               clearInterval(timer) 
               this.isTimerStart = false;
               console.log("lets Save it")
               this.saveRunningMethod()
               });

           if(this.mSecond < 9)
                this.mSecond +=1
            else
                this.mSecond=0

           if(this.mSecond==9)
                this.second +=1                

            if(this.second>59)                   
                this.second=0

            if(this.second==59)
                this.minute +=1

            if(this.minute>59)
                this.minute=0

            if(this.minute==59)
                this.hour+=1             

    },100);

    }
}

In the code above,

e.addEventListener("click", function(){
is used to stop the timer when clicking on the 'stop' button. However, this method seems to be running multiple times and resulting in multiple executions of console.log as depicted in this image: https://i.sstatic.net/z5vLR.jpg

Another issue I am facing is with the line: this.saveRunningMethod(). When I try to call this method within my startTimer() method, I receive an error stating "this.saveRunningMethod() is not a function."

Finally, for the timer setup utilizing setInterval, if you have any suggestions for a more efficient solution, your input would be greatly appreciated.

UPDATE: Including my HTML component below:

<div class="row p-2 m-3 mt-3">
        <div class="col-12 p-0 animated fadeInUp mt-3">
            <p class="text-center">Your last record was : 00:00:00</p>
        </div>
        <div class="col-12 p-0 animated fadeInUp mt-3">
            <h1 class="text-center timer">
                {{this.hour}}:{{this.minute}}:{{second}}:{{mSecond}}
            </h1>
        </div>
    </div>
    <div class="row p-2 mt-3" v-bind:class="[this.isTimerStart==false ? 'show' : 'hide']">
        <div class="col-12 p-0 animated tada text-center">
            <button class="btn-link timerImg" @click="startTimer()">
                <img class="img-fluid timerImg" src="../../static/timerStart.png" />
                <p>Start</p>
            </button>
        </div>
    </div>

    <div class="row p-2 mt-3" v-bind:class="[this.isTimerStart ? 'show' : 'hide']">
        <div class="col-12 p-0 animated tada text-center">
            <button id="stopBtn" class="btn-link timerImg">
                <img class="img-fluid timerImg" src="../../static/timerStop.png" />
                <p>Stop</p>
            </button>
        </div>
    </div> 

Thank you for your assistance.

Answer №1

As per the information from a reliable source, the functionality of window.setInterval() is as follows:

It repeatedly calls a specified function with a fixed time delay between each call.

When the method startTimer() is triggered, it attaches a click event listener to the stop button every 100 milliseconds. Thus, if there is a 3.3-second delay before clicking the stop button after page load, the click event will have been added to the button 33 times:

var timer = window.setInterval(() => {

    var e = document.getElementById("stopBtn")
    e.addEventListener("click", function() {
        // This code will run 33 times on stop button click.
    })
    ...
}, 100)

If there is a 5.4-second delay prior to clicking the stop button after loading the page, the click event will have been attached to the button 54 times!

Rather than utilizing window.setInterval(), it is recommended to use window.setTimeout(). As stated by this resource, this is its purpose:

It executes a code snippet or a function after a specified delay.

In essence, window.setTimeout() sets up a timer that runs only once after a user-specified delay.

Regarding the error mentioning "

this.saveRunningMethod() is not a function
," the issue arises due to context changes within the callback function passed to addEventListener(). The value of this switches to the button itself rather than your object. To circumvent this problem, an arrow function can be passed to addEventListener(), maintaining the context unchanged (thus keeping this as your object inside the arrow function):

window.setTimeout(() => {
    var e = document.getElementById("stopBtn")
    e.addEventListener("click", () => {
        this.isTimerStart = false;
        console.log("Saving now");
        this.saveRunningMethod();
    });
}, 100)

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

Unable to include an additional parameter within a JavaScript function

I'm having trouble adding a parameter to the Openpopup() function - every time I try, I get an error. Can someone help me out with this? Thanks in advance. return "<a onclick='return Openpopup()' class='btn btn-info btn-lg clickBtn& ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Issue with Docker: PhpStorm Vue syntax highlighting disappears shortly after loading

I am experiencing an issue where the PhpStorm Vue syntax highlighting disappears after a few seconds. Despite installing the Vue plugin for my IDE and trying various troubleshooting steps such as restarting PhpStorm, checking plugin settings, and invalida ...

The query callback does not recognize 'done' as a function, leading to a

I'm attempting to save the result of a query into a variable. I've learned that using a callback is necessary for this task. However, I am encountering errors in the process. function fetchUserData(user) { if (user.checkUserStatus) { var u ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Exploring Vue.js with the composition API, delving into the world of "Mixins" and mastering life-cycle hooks

I've been searching everywhere (and coming up empty-handed) for a solution to the following question. In Vue 2.x, I was able to utilize mixins for life-cycle hooks. For example, I could create a file Mixins.js with: export default { created() { ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

What is the best way to make a div pull its background image directly from the internet instead of using the cached version?

Running relevant Javascript every fifteen minutes to fetch the appropriate image from the internet: document.getElementById('weatherbug').style.background = "url('http://tinyurl.com/jwltx5s') repeat scroll -1px -24px transparent"; The ...

Ensuring the accuracy of query parameters in REST api calls using node.js

Each object type in the GET request to the API has a set of valid query parameters. var queryFields = { 'organisation': ['limit', 'page', 'id', 'search'], 'actor': ['limit', 'p ...

Displaying numerous database rows through SQL with the aid of PHP and JavaScript (specifically AJAX) on the frontend of a website

I am a beginner in the world of PHP and JavaScript (Ajax) and despite my efforts to find a solution by looking at various posts and websites, I have not been successful. My goal is to display all related database rows on the front end of a website. While ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

What is causing the local storage to not persist after refreshing the page?

Even after a browser refresh, the button text 'completed' should remain intact depending on whether the variable item is true (after the button click). I have experimented with Chrome and believe the issue is not related to the browser. <temp ...

nuxt-link: take me to the identical position with the hash in the URL

I'm facing an issue with the <nuxt-link> component in my Nuxt application: The first time I click on the link, everything works perfectly and the page is changed as expected. However, if I scroll down a bit and try clicking the link again, noth ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...