js two timer, a loop is executed the setInterval , the other is a timing performed setTimeout
A repeatedly executed ( the setInterval)
As the name suggests, it is to set up a loop execution time interval, every once in a while will be executed once this method until the timer is destroyed out
Usage is setInterval ( "method or method", "delay"), the first parameter is the name of the method or methods, pay attention to the method name when not in parentheses, and the second parameter is the time interval
<template> <section> <h1>hello world~</h1> </section> </template> <script> export default { data() { return { timer: '', value: 0 }; }, methods: { get() { this.value ++; console.log(this.value); } }, mounted() { this.timer = setInterval(this.get, 1000); }, beforeDestroy() { clearInterval(this.timer); } }; </script>
The above example is the initial page when creating a timer setInterval , time interval of 1 second, every second will be called once the function get, so that the value of the value plus one.
Second, the timing of execution (the setTimeout)
The timing of execution setTimeout time is to set a time, waiting for the arrival time is performed only once, but after executing the timer is still there, but not running
Usage is the setTimeout ( "method or method", "delay"); The first parameter is the name of the method or methods, pay attention to the method name when not in parentheses, and the second parameter is the time interval
<template> <section> <h1>hello world~</h1> </section> </template> <script> export default { data() { return { timer: '', value: 0 }; }, methods: { get() { this.value ++; console.log(this.value); } }, mounted() { this.timer = setTimeout(this.get, 1000); }, beforeDestroy() { clearTimeout(this.timer); } }; </script>
The above is initialized when the page is to create a timer the setTimeout , the method only once after 1 second.
Timers need to be cleared when the page destroyed out (execution beforeDestroy), otherwise will always exist! ! !