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

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!");
}

Related

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

How can I reset a settimeout

I tried the answer here: Resetting a setTimeout, but it doesn't seem to be working for me.
I'm building a catalog viewer using Owl Carousel. I have a function set to go off on the afterMove event handler that shows what page the user is on. It displays the page counter and then sets a timeout to have it fadeout after 1 second. Probably is lots of people go through pages faster than once per second. So, I need to reset the timeout if the function gets called again.
function showCounter(){
var $counter = $('#counter');
//clear timeout
window.clearTimeout(timeout);
//Display counter
$counter.show();
//set timeout
var timeout = window.setTimeout(function(){
$counter.fadeOut(500);
}, 1000);
}
But window.clearTimeout(timeout) doesn't seem to be working and I'm not sure why
Thanks
var timeout inside the function makes timeout local to the function; thus, every time you call showCounter, timeout is undefined. Move the variable declaration out of the function:
var timeout;
function showCounter() {
// ...
timeout = // NO VAR! ...
// ...
}

setInterval in javascript based on changes made

I'm having an issue with a javascript requirement. I have a html calling a script perpetually every 1500ms using setInterval.
var t = setInterval(loadData(),1500);
The loadData function calls a script which returns a JSON as a list, what I want to do is to change from a fixed interval to a variable interval. For instance, if there are no changes made between two calls to the script, I must set another value for the interval. I heard I could use jquery linq to compare the length of the list at the beginning and the list when refreshing to change the time value. I also heard I could save the value of count in a cookie to compare always.
Any idea please? I would be grateful. Thanks in advance.
I'm guessing you're trying to do:
var speed = 1500,
t = setInterval(loadData, speed);
function loadData() {
if (something == true) {
something = false;
speed = 3000;
clearInterval(t);
t = setInterval(loadData, speed);
}else{
//do something
}
}
You should just reference the function, adding the parenthesis runs the function immediately. When using a variable for the speed, you'll need to clear and run the interval function again to change the speed.
if the interval is variable, then you can't use setInterval, which period won't be changed after the first call. You can use setTimeout to alter the period:
var period=1500
var timer;
var callback = function() {
loadData();
timer = setTimeout( callback, period )
};
var changePeriod = function( newPeriod ) {
period = newPeriod;
}
//first call
callback();
now, you just need to call changePeriod( ms ) to change the period afterwards

Cant get javascript intervals to work

so im a little new to javascript, but im trying to make a progress bar, with some other functionalities, on click of a button. im tring to use the set interval in javascript in order to time the bar, this is my js so far:
//Javascript Document
function progress(){
Var uno = setTimeout("uno()", 3000);
uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
}
From what i have gathered this is how it works, however i am skeptical as it seems i am setting a variable uno but not doing anything with it.... from my background in php, thats not how that works :p any pointers you guys can give me on this? my html is here: http://jsbin.com/apoboh/1/edit
right now, it does nothing, it gives me : Uncaught ReferenceError: progress is not defined
first, you are using setTimeout not setInterval. The former fires the callback once, the latter indefinitely at a set interval.
Second, these methods return a token that you can use to cancel a setInterval, do this instead
function startProgress(){
// only start progress if it isn't running
if (!App.progressToken) { // App is you apps namespace
App.progressToken = setInterval(function(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}, 3000);
}
}
later, when you want to stop:
function stopProgress(){
clearInterval(App.progressToken);`
delete App.progressToken
}
The variable uno simply holds the handle to the timeout that you just set. You can later use it to clear the timeout before it executes if you need to via a call to clearTimeout().
If you don't need to clear the timeout, then there's really no reason to store the handle at all.
function progress(){
function uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
var timeoutFunc = setTimeout(uno, 3000);
}
You pass a function to setTimeout which it will call later, not a string. So this code will define a function uno, and then pass it to setTimeout and delay 3 seconds then call it every 3 seconds after that.
You forgot to put word "function " before uno()

How to pause a setTimeout call? [duplicate]

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

Categories

Resources