[Vuejs]-How to stop function in 5 seconds? Vue.js

1๐Ÿ‘

โœ…

The following code runs a task every 250ms and stops after 5sec. I hope this will give you some inspiration.

var intervalId = setInterval(() => console.log("running"), 250);
setTimeout(() => clearInterval(intervalId), 5000);

0๐Ÿ‘

Here is your mistake: do not use this without being careful: you should take time to understand how this works in JavaScript.

In your code, you increment this.timesRun, but you test on timesRun which is never incremented.

This sample will work as you expect:

let timesRun = 0; 
//const addImage = this.addImage;
const intervalAddImage = setInterval(function () {
  timesRun += 1;
  if (timesRun === 60) {
    clearInterval(intervalAddImage);
  }
  //addImage();
  console.log("Hello", timesRun);
}, 250);

0๐Ÿ‘

So it works)

let timesRun = 0; // just change to this
function addImage(timesRun) { console.log(timesRun)}
const intervalAddImage = setInterval(function () {
    timesRun += 1; // just change to this
    if (timesRun === 4) {
        clearInterval(intervalAddImage)
        return; // add this
    }
    addImage(timesRun);
}, 250);

Leave a comment