How to pause a setTimeout call? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript: pause setTimeout();
Im using jQuery and working on a notification system for my site. The notifications automatically fadeout using the setTimeout function.
How can i stop the timer of the setTimeout call?
For example i would like to pause the setTimeout call while the mouse is over the notification and continue the count down mouseout...
I googled "pause setTimeout" with no luck.
Im currently clearing the setTimeout call with clearTimeout and at same time fading out the notification on mouseout but it would be nice to have that pause effect.
Any ideas?

Try this.
var myTimeOut;
$(someElement).mouseout( function () {
myTimeOut = setTimeout("mytimeoutfunction()", 5000)
});
$(someElement).mouseover( function () {
clearTimeout(myTimeOut);
});

It wouldn't be too hard to add a PausableTimeout class:
(Might not be valid JS, but it shouldn't be too hard to get it working):
function PausableTimeout(func, millisec) {
this.func = func;
this.stTime = new Date().valueOf();
this.timeout = setTimeout(func, millisec);
this.timeLeft = millisec;
}
function PausableTimer_pause() {
clearTimeout(self.timeout);
var timeRan = new Date().valueOf()-this.stTime;
this.timeLeft -= timeRan;
}
function PausableTimer_unpause() {
this.timeout = setTimeout(this.func, this.timeLeft);
this.stTime = new Date().valueOf();
}
PausableTimer.prototype.pause = PausableTimer_pause;
PausableTimer.prototype.unpause = PausableTimer_unpause;
//Usage:
myTimer = new PausableTimer(function(){alert("It works!");}, 2000);
myTimer.pause();
myTimer.unpause();
Of course, it'd be a great idea to add some error checking in there (don't want it to be possible to unpause the timeout multiple times and end up with hundreds of timeouts!), but I'll let that be your job :P

Use clearTimeout() on mouseover event and use setTimeout() again on mouseout event.
http://www.w3schools.com/jsref/met_win_cleartimeout.asp

Related

How to make functions get called sequentially in JS? [duplicate]

This question already has answers here:
Wait until setInterval() is done
(6 answers)
Closed 2 years ago.
I am making a webpage where once the user clicks on the start button, some changes will happen to the CSS of the page (I wrote the required JavaScript (JS) code). Only after these changes happen, I want some other changes to happen. In an attempt to achieve this, I wrote calls to 2 functions inside the function that gets called once the event happens: (In the below JS code, the 2 functions begin called inside the function that which gets triggered by the "click" event are- startCountdown and showWords)
document.getElementById("startButton").addEventListener("click",startTheGame);
function startTheGame()
{
var contentSlides = document.getElementsByClassName("slide");
// Game started so we are hiding the start slide!
contentSlides[0].classList.add("hideDisplay");
//
// Now the "321 Go!" down timer is to be shown!
contentSlides[1].classList.remove("hideDisplay");
startCountdown(document.getElementById("onClickCount"));
showWords();
//
}
function startCountdown(reqElement)
{
var time = 2;
var intervalId = setInterval(function ()
{
reqElement.innerText = time;
if(time==="Go!")
clearInterval(intervalId);
time-=1;
if(time===0)
time = "Go!";
},1000);
}
function showWords()
{
alert("Hi!");
}
In the showWords function also, I wish to make some changes to the page. But, I want it to get executed only after the startCountdown function gets executed completely. As of now when I am running the above code, as soon as I click on the button, the alert is popping up! - But I don't want it to happen.
What changes do I need to make?
(After the showWords function gets executed completely - I want one more function to be executed - in this way I want the functions to be executed sequentially - i.e. the changes must happen in a specific order.)
Thanks for the help!
P.S.: Please let me know if you aren't able to understand my question.
so when it's called clearInterval like this
document.getElementById("startButton").addEventListener("click",startTheGame);
function startTheGame()
{
var contentSlides = document.getElementsByClassName("slide");
// Game started so we are hiding the start slide!
contentSlides[0].classList.add("hideDisplay");
//
// Now the "321 Go!" down timer is to be shown!
contentSlides[1].classList.remove("hideDisplay");
startCountdown(document.getElementById("onClickCount")); //
}
function startCountdown(reqElement)
{
var time = 2;
var intervalId = setInterval(function ()
{
reqElement.innerText = time;
if(time === 0){
clearInterval(intervalId);
reqElement.innerText = "Go!"
showWords();
}
time--;
},1000);
}
function showWords()
{
alert("Hi!");
}

Execute javascript function every second while the button is pressed [duplicate]

This question already has answers here:
JavaScript while mousedown
(3 answers)
Closed 4 years ago.
I need to execute a javascript function continuosly (every second or half a second for example), but this needs to happen while a button is pressed.
I tried with the following:
$("#buttonID").bind('touchstart',function(event){
setInterval(function() {
FUNCTION
}, 1000);
});
It is not working that way, using "mousedown" either.
What it's answered on question JavaScript while mousedown
did not solve my issue, so I don't consider this question as a duplicate.
Is there a beginner's mistake and I'm not seeing it? what do you suggest?
You have to capture a reference to the timer and cancel it when the mouse is released.
var timer = null; // Will hold a reference to the timer
$("#buttonID").on('mousedown',function(event){
// Set the timer reference
timer = setInterval(function() {
console.log("Function running");
}, 1000);
});
$("#buttonID").on('mouseup',function(event){
clearInterval(timer); // Cancel the timer
console.log("Timer cancelled.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonID">Hold me down to run function!</button>

Stop a setTimeout function in AngularJS (hint: use $timeout)

I'm making a quiz-type app in which, when user gets a question, a timer of 10 seconds goes like this:
$scope.timer2 = function() {
setTimeout(function() {
console.log('times up!!!!');
}, 10000)
}
and it is being called when a question arrives like this:
timerHandle = setTimeout($scope.timer2());
And after this timer2 execution another question pops up and so on, another way of a question being popped up is that the user selects an option also then a new question comes up. So far so good but the problem is that if suppose 5 seconds were passed and then user selects an option, the "timer2" still shows "times up!!" after 5 more seconds and another timer for the new question also shows "times up!!" if the user hasn't selected any option.
What I'm trying to say is that I want the timer2 to stop when user selects any option, and then i want again this timer to be called as a new question will arrive.
This is the angular code which executes when user selects an option:-
$scope.checkanswer=function(optionchoosed){
$http.get('/quiz/checkanswer?optionchoosed='+ optionchoosed).then(function(res){
if(res.data=="correct"){
$scope.flag1=true;
$scope.flag2=false;
}else{
$scope.flag2=true;
$scope.flag1=false;
}
$http.get('/quiz/getquestions').then(function(res){
console.log("respo");
$scope.questions=res.data;
clearTimeout($scope.timerHandle); //not working
timerHandle = setTimeout($scope.timer2());
You can try using the service of AngularJS $timeout.
Then do something along these lines:
var myTimer = $timeout(function(){
console.log("hello world")
}, 5000);
....
$timeout.cancel(myTimer);
Take a look at the MDN documentation for setTimeout.
As you can see, that function returns a unique identifier.
At this point, you can call clearTimeout passing that UID as parameter:
let myTimeout = setTimeout(myFunction, millis); //Start a timeout for function myFunction with millis delay.
clearTimeout(myTimeout); //Cancel the timeout before the function myFunction is called.
Since you do not provide working example let me do the best guess. Your function does not return handle from inner setTimeout so it cannot be cancelled. What about such modifications:
$scope.timer2 = function() {
return setTimeout(function() { // added return statement
console.log('times up!!!!');
}, 10000)
}
and then
timerHandle = $scope.timer2(); // simply call timer2 that returns handle to inner setTimeout

request animation frame loop

I came across this code
https://gist.github.com/joelambert/1002116 and i thought of playing around with it
I tried to create a loop and stop it
var tick = 0;
var dor = requestInterval(function(){
tick++;
console.log("hi", tick)
if (tick > 10){
stop();
}
},300)
function stop(){
console.log("stop")
clearRequestInterval(dor);
}
But the clearRequestInterval is not clearing the timer. But when i tried to call it from a button's event handler its working. Am I missing something?
I have attached a codepen
http://codepen.io/srajagop/pen/KgbbpR
#Bergi is right that the example code you tried to use is broken, it doesn't support cancelling the interval timer from within the interval function itself. You can work around that by invoking the clearRequestInterval asynchronously:
function stop() {
console.log("stop");
window.setTimeout(function() {
clearRequestInterval(dor);
}, 0);
}
Or perhaps better, you could fix the example code not to reschedule itself even if it was cancelled from within the interval function.

Stopping a running function in javascript/jquery on click event

I have a slideshow function in jquery that I want to stop on a particular click event. The slideshow function is here:
function slider(){
setInterval(function(){
var cur = $('img.active');
cur.fadeOut('fast');
cur.removeClass('active');
cur.css('opacity','0');
cur.addClass("hidden");
var nextimg;
if (!cur.hasClass("last")){
nextimg = cur.next("img");
}
else {
nextimg = cur.prev().prev().prev();
}
nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
},5000);
}
I have been reading about .queue but not sure how I can use it exactly, can I call my function from a queue and then clear the queue on a click event? I cannot seem to figure out the syntax for getting it to work of if thats even possible. Any advice on this or another method to stop a running function on a click would be appreciated.
For what it's worth, it's generally advisable to use a recursive setTimeout instead of a setInterval. I made that change, as well as a few little syntax tweaks. But this is a basic implementation of what I think you want.
// Store a reference that will point to your timeout
var timer;
function slider(){
timer = setTimeout(function(){
var cur = $('img.active')
.fadeOut('fast')
.removeClass('active')
.css('opacity','0')
.addClass('hidden'),
nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
nextimg.removeClass('hidden')
.fadeIn('slow')
.css('opacity','1')
.addClass('active');
// Call the slider function again
slider();
},5000);
}
$('#someElement').click(function(){
// Clear the timeout
clearTimeout(timer);
});
Store the result of setInterval in a variable.
Then use clearInterval to stop it.
Store the value returned by setInterval, say intervalId to clear it, your click handler should look like this:
function stopSlider() {
//prevent changing image each 5s
clearInterval(intervalId);
//stop fading the current image
$('img.active').stop(true, true);
}

Categories

Resources