[Vuejs]-How to stop randomly Timeout function

1👍

The documentation for clearTimeout clearly shows that the only parameter is an ID provided by a setTimeout.

If you want to stop your “loop”, firstly you need to pass the correct value, in your case it’s clearTimeout(this.tessst).

If you want that clearTimeout to be fired after a random amount of time, then you need another setTimeout… see, the below example which you can run.

var count = 0;
var timerId = null;
function startTimer() {
  console.log(++count);
  timerId = setTimeout(startTimer, 1000);
}
function stopTimer() {
  var rnd = Math.floor(Math.random() * 5000);
  console.log("Stopping in " + (rnd / 1000) + " seconds");
  setTimeout(function() {
    clearTimeout(timerId);
    console.log("Stopped");
  }, rnd);
}
startTimer();
<input type="button" onclick="stopTimer();" value="Stop" />

Leave a comment