Repeatedly execute JavaScript code with setInterval
Published on 2020-05-06 • Modified on 2020-05-06
This function is the sibling of the setTimeout
function we saw in the previous snippet. This time it will allow us executing some code repeatedly with a given delay thanks to a snippet or a callback. Click on the start button to display a message in the console every second. Then, click on the stop button to stop the execution of the code. I have added a random number for each to see a different output for every call of the function.
/**
* I am using a JavaScript module to isolate the code of each snippet.
* In fact it's a Vue.js mixin. Take the code called by the mounted()
* or the snippetXX() function.
*/
export default {
data: {
interval: null
},
methods: {
snippet89 () {
console.log('Starting interval...')
this.interval = setInterval(function () {
console.log('Hello world! 🐝 > ' + Math.random())
}, 1000)
},
stopSnippet89 () {
console.log('Interval stopped.')
clearInterval(this.interval)
}
}
}
HTML demo of the snippet
More on Stackoverflow Read the doc Random snippet