Problem Description

In some demand development, it is necessary to set the time period (business hours) during which the software provides services. At this time, you can choose a timer to implement it, and you can choose to have the timer detect whether the current time is within the service time every once in a while. The service time is reached and the service state is entered. The service time has not yet arrived and the non-service time period has entered. Problems you may encounter? When operations such as switching and exiting different services require multiple passes through the timer method, the consequence is that the timer is started multiple times. Causing page functionality to become confusing. How to solve this problem? The method is very simple, that is, before turning on the timer, first turn off the last turned on timer (write the timer that clears the last setting directly before turning on the timer code). In this way, no matter how many times you start the timer, you can always keep only one timer working.

solution

Conclusion: Use global variables instead of definitions in data

<!DOCTYPE html>
<html>

<head>
     <meta charset="UTF-8" />
     <title>Timer</title>
     <!--Introduce vue -->
     <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
     <div id="App">
         <h1>Current num: {{num}}</h1>
         <button @click="startTimer()">Click me to start the timer</button>
         <button @click="StopTimer()">Click me to turn off the timer</button>

     </div>
     <script type="text/javascript">
         Vue.config.productionTip = false //Set to false to prevent vue from generating production tips on startup
         let timerd = null

         //Create Vue instance
         newVue({
             el: '#App',
             data: {
                 value: "Vue",
                 newTime: '',
                 num: 1,
                 // timerd: ''

             },
             methods: {

                 StopTimer() {
                     console.log("The value of the currently closed timer: " + timerd)
                     clearInterval(timerd)
                 },
                 startTimer() {
                     console.error("Timer turned on")
                     timerd = setInterval(() => {
                         this.num++
                     }, 1000)

                     console.log("Current timer value: " + timerd)
                 }
             },
         })
     </script>

</body>

</html>
Likes(1)

Comment list count 0 Comments

No Comments