How can I create a pause and resume function setTimeout()?

Asked

Viewed 564 times

0

I need to create a kind of pause and resume, can be with Javascript (without jQuery).

I have a slide photos, each photo appears every 3 seconds with setTimeout() and in this way (as they see the functions are chained to not happen delays):

setTimeout(function() {
  //mostrar uma imagem

  setTimeout(function() {
    //mostra outra

    setTimeout(function() {
      //assim sucessivamente...
    }, 3000);
  }, 3000);
}, 0);

So I searched some help forums and found only one function that stops the script, but it wasn’t helpful because I need something to pause the setTimeout and soon after I can give a resume again, I even tried a function Timer() with object orientation, however it only works once it is not possible to chain the functions as I did with setTimeout().

See the tests I did and some functions I tried to use one more only worked once to pause the Timer(), note that I added a onload to load some alerts if I use the Timer to pause they only pause one setTimeout, not pause all, and I want to pause all of them at once and when press on return it returns from where it stopped in setTimeout();

<!DOCTYPE html>
<html>
<head>
	<title>Funções de Tempo</title>
	<script type="text/javascript">
		function alertas() {
			// var timer = new Timer(function() {
			// 	alert('Tempo Final');
			// }, 10000);

			setTimeout(function() {
				alert('1 vez');

			setTimeout(function() {
				alert('2 vez');

			setTimeout(function() {
				alert('3 vez');
			}, 3000);
			}, 3000);
			}, 3000);
		}
		function Timer(callback, delay) {
		    var timerId, start, remaining = delay;

		    this.pause = function() {
		        window.clearTimeout(timerId);
		        remaining -= Date.now() - start;
		    };

		    this.resume = function() {
		        start = Date.now();
		        window.clearTimeout(timerId);
		        timerId = window.setTimeout(callback, remaining);
		    };

		    this.resume();
		}

		// var timer = new Timer(function() {
		//     alert("Done!");
		// }, 1000);

		var timer = new Timer(function() {
			alert('ok');
		}, 3000);

		// timer.pause();
		// Do some stuff...
		// timer.resume();
		function pausar() {
			alert('pausado!');
			timer.pause();
		}
		function continuar() {
			alert('Retornando');
			timer.resume();
		}
		function sleep(milliseconds) {
		  var start = new Date().getTime();
		  for (var i = 0; i < 1e7; i++) {
		    if ((new Date().getTime() - start) > milliseconds){
		      break;
		    }
		  }
		}
	</script>
</head>
<body onload="alertas()">
   <button onclick="pausar()">Pausa</button>
   <button onclick="continuar()">Retornar</button>
   <!-- <button onclick="iniciar()">Iniciar</button> -->
</body>
</html>

  • can’t take a "break" in the setTimeout, What you can do is cancel with the clearTimeout and control your break in a loop or event, and when the break is over, start again the setTimeout. Detail: to do this, associate the setTimeout to a variable

  • Thanks Ricardo, I’ll try to do this!

  • I did not quite understand the summary part, but in that case it would not be better to use setInterval() instead of setTimeout()?

  • I don’t know exactly how the setInterval() works, I almost thought that its function would be almost the same as the setTimeout

  • I can give a search on it, but what I really need is a button in the html that pause and the summary in setTimeout, the same as if it was a video you pause and play again to continue

  • It is not "abstract", it is "resumed".... the word "abstract" means "synthesis", something shorter, summarized. The English term "resume" does not mean "abstract". It’s a false cognate.

  • Would that be https://jsfiddle.net/z7dsk32a/ ? - taking advantage, setTimeout runs something only once, while setInterval runs indefinitely, or until interrupted by a clearInterval. Finally, read: https://answall.com/q/77764/112052

Show 2 more comments

1 answer

0

You could create a class timer.

Example:

function mytimer() {
  this.time = 0;
  this.pause = false;
  this.update = function() {
    if (!this.pause) {this.time += 1};
      slide();
}
  this.intervalo = setInterval(this.update,1000);
}
var myslide = new mytimer();
function slide() {
  if (myslide.time == 3) {
    alert("Slide 1");
}
  if (myslide.time == 6) {
    alert("Slide 2");
}
  if (myslide.time == 9) {
    alert("Slide 3");
    myslide.pause = true;
  }

}

function pause() {
  myslide.pause = true
}
function resume() {
myslide = false;
}

Or

setTimeOut(myfunction,3000);
var time = {
  value: 0,
  pause: false
}
function myfunction() {
  if (!time.pause) {
   time.value += 1;
   if (time.value == 1) {
    alert("Slide 1");
   }
  if (time.value == 2) {
    alert("Slide 2");
  }
  if (time.value == 3) {
    alert("Slide 3");
    time.pause = true;
  }
   setTimeOut(myfunction,3000);
  }
}
function pause() {
  time.pause = true
}
function resume() {
  time.pause = false;
  setTimeOut(myfunction,3000);
}
  • Hello thanks for the help, I will do some tests using these functions as soon as I can and return later if it worked.

  • You can also add other tools in the class: Reset time, team name and etcs. If you want to pass the full code.

  • Thanks, if you can send me yes please, but I see that I will need to study the structure a little to understand how it is working, because just looking at it can not to know if it will really work you know, just testing in practice even, if I can share my result here rs

  • https://gitlab.com/maurygta2/timer_js/blob/master/timer.js My school project you can read,ta confused, because that was my first code.

  • Thanks rs, then I give a study on it.

  • Do not use greetings or greetings, see what kind of behavior is expected from users?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.