Run function when other function is completed - javascript

Im looking for a way to run a function when the other function is ready.
This is the function:
$(".box").first().show(150, function showNext () {
$(this).next(".box").show(150, showNext);
});
So Im look for a way to run another function after that, for example:
alert("Done");
I've tried this but didn't work.
$(".box").first().show(150, function showNext () {
$(this).next(".box").show(150, showNext);
}, function () {
alert("Done");
});
What I want is, in words:
if(all .box is visble or if showNext is idle/completed){
alert("Done");
}
I appreciate any help! Thanks.

How about :
$(".box").first().show(150, function showNext () {
var next = $(this).next(".box");
if (next.length > 0) { // If a next sibling with class "box" was found
next.show(150, showNext);
} else { // No sibling found, end reached
alert("Done");
}
});

Related

Trouble with jQuery events and function triggers

Let me explain what the trouble is. I have two functions: compute(); and discount_compute();. When the page firsts load both functions get executed once (OK, since discount_compute() is part of compute so it always runs when compute() is executing). When I open the #autobid-panel (it is set on display:none initially) the function discount_compute runs 1 time because of the $('#autobid').on('click', function(), but then it also runs 2 more times because of the '[data-slider]').on('change.fndtn.slider'). Btw everytime this autobid-panel is closed or opened the slider is initialized again. I only want the discount_compute() to run once when #autobid-panel is opened. Any ideas?
function compute() {
//first function
};
function discount_compute() {
//second function
};
$(document).ready(function($) {
$('.price').change(compute).change();
$('#autobid').on('click', function() {
if ($(this).is(':checked')) {
$('#autobid-panel').removeClass("hide");
$(document).foundation('slider', 'reflow');
discount_compute();
} else {
$('#autobid-panel').addClass("hide");
$(document).foundation('slider', 'reflow');
}
});
$('#discount').on('change', function(){
var value = $(this).val();
$('.range-slider').foundation('slider', 'set_value', value);
discount_compute();
});
$('[data-slider]').on('change.fndtn.slider', function(){
discount_compute();
});
});
Thank your for your help!
You don't really explain the reasoning of the data-slider or why you even call discount_compute(); there if you don't want to run it.
One dirty hack you can do is something to this effect:
function compute() {
//first function
};
function discount_compute() {
//second function
};
var harRun=false;
$(document).ready(function($) {
$('.price').change(compute).change();
$('#autobid').on('click', function() {
if ($(this).is(':checked')) {
$('#autobid-panel').removeClass("hide");
$(document).foundation('slider', 'reflow');
if(hasRun != true) {discount_compute(); hasRun=true;}
} else {
$('#autobid-panel').addClass("hide");
$(document).foundation('slider', 'reflow');
}
});
$('#discount').on('change', function(){
var value = $(this).val();
$('.range-slider').foundation('slider', 'set_value', value);
discount_compute();
});
$('[data-slider]').on('change.fndtn.slider', function(){
if(hasRun != true) {discount_compute();}
});
});
In this way, once hasRun is set to true you no longer call discount_compute().
unfortunately $(document).foundation('slider', 'reflow'); fires a change event, so there isn't any nice way.
one way is to off the event before reflow and on straight after:-
function compute() {
//first function
};
function discount_compute() {
//second function
};
$(document).ready(function($) {
$('.price').change(compute).change();
$('#autobid').on('click', function() {
if ($(this).is(':checked')) {
$('#autobid-panel').removeClass("hide");
$('[data-slider]').off('change.fndtn.slider', discount_compute);
$(document).foundation('slider', 'reflow');
$('[data-slider]').on('change.fndtn.slider', discount_compute);
discount_compute();
} else {
$('#autobid-panel').addClass("hide");
$(document).foundation('slider', 'reflow');
}
});
$('#discount').on('change', function(){
var value = $(this).val();
$('.range-slider').foundation('slider', 'set_value', value);
discount_compute();
});
});

How to make this script pause on hover?

I'm new to jQuery and I need a bit of help. I'm using this jQuery script as a testimonial rotator and it works like a charm but I just need to make one small tweak. I need it to be able to pause on hover and then restart when the mouse leaves the div. How can I do this?
This is the script I'm using:
function fadeMyContent() {
$(".testimonial:first").fadeIn(1000).delay(3000).fadeOut(1000,
function() {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}
fadeMyContent();
});
Here is a JSFiddle.
There is a plugin that will provide all the functionality you need and be more reliable called jQuery Cycle 2.
It provides a 'pause-on-hover' option when initialising it.
change the definition of fadeMyContent (also called as destroying function) on hovering on ul#testimonial-rotator and on hover-out change it to old definition again. I have used setTimeout in place of delay because delay is not cancellable.
$(document).ready(function () {
var fadeMyContent;
var t
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
var fadeMyContentDummy = function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent()
});
}
fadeMyContent();
$('#testimonial-rotator').hover(function (e)
{
window.clearTimeout(t)
$('.rotate:first').clearQueue()
fadeMyContent = function () {
return false;
}
},
function (e)
{
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
fadeMyContentDummy()
})
});
DEMO

How do you call a function once all iterations using .each() has occurred?

Below is a snippet which I need help on. I want to call a function once all the span's have been iterated through. So an example would be if I had 8 spans's, after the 8th span's function has been run, how do I call nextFunction()?
$('#div1').animate({ opacity: '0.2' }, 500, function () {
$('span').each(function () {
//do something.
});
nextFunction();
});
function nextFunction() {
alert("called after the last .each() has occurred");
};
Try $.when()
$('#div1').animate({
opacity: '0.2'
}, 500, function () {
$.when($('span').each(function () {
//do something.
})).then(function () {
nextFunction();
});
});
function nextFunction() {
alert("called after the last .each() has occurred");
};
The code should actually run sequentially, just the way you have written it, unless you're planning to use AJAX requests in the .each() loop.
Something like this
$('#div1').animate({ opacity: '0.2' }, 500, function () {
var doSomething = 0,
ctx = null,
checker = null;
checker = function() {
if (domSomething === $('span').length)
{
clearTimeout(ctx);
nextFunction();
return ;
}
setTimeout(checker, 100);
};
$('span').each(function () {
doSomething += 1;
//do something.
});
checker();
});
.each() is synchronous. It will work the way you have it. See this fiddle

Unexpected token ILLEGAL when using setTimeout/Cleartimeout

This is what i want: Timeout when i hover out of a div, cancel if i hover on top of the div again.
The code works if i remove the cancelfunction. So showing and hiding the div works fine.
This is my code:
$(document).ready(function ()
{
var timeoutID;
function clearAlert()
{
window.clearTimeout(timeoutID);
}​
if ($('.txtVote').text() == "Avgi stemme")
{
$('#starInfo').hover(
function ()
{
clearAlert();
$('#CarDetailsButtons').css('right', '10px');
$('#voteStars').show();
},
function ()
{
console.log("hide iniated");
timeoutID = window.setTimeout(hideStars, 2000);
console.log("hide executed");
});
}
function hideStars()
{
console.log("hideStars ran");
$('#CarDetailsButtons').css('right', '45px');
$('#voteStars').hide();
}
});
And, this is my error:
Uncaught SyntaxError: Unexpected token ILLEGAL
which appears on the line right after window.clearTimeout(timeoutID);
Anyone able to see what I'm doing wrong? :)
EDIT: *WORKS*
So, it seems i had some kind of copy paste bug. I wrote the function clearAlert manually, just like it was before, and it works now.
Thanks for all the input!
try this:
var that = this;
that.timeoutID = null;
...
that.timeoutID = ...
OR
you have to declare var timeoutID = null; global. So you have the var in a gloabl context and not within the function-context of $(document).ready.
the best solution ist to write a little js-class with the timer in it. so you have no global conflicts an it works.
greetings!
I would suggest you to move your functions outside of doc ready like this:
function hideStars()
{
console.log("hideStars ran");
$('#CarDetailsButtons').css('right', '45px');
$('#voteStars').hide();
}
function clearAlert()
{
window.clearTimeout(timeoutID);
}​
$(document).ready(function ()
{
var timeoutID;
if ($('.txtVote').text() == "Avgi stemme")
{
$('#starInfo').hover(
function ()
{
clearAlert();
$('#CarDetailsButtons').css('right', '10px');
$('#voteStars').show();
},
function ()
{
console.log("hide iniated");
timeoutID = window.setTimeout(hideStars, 2000);
console.log("hide executed");
});
}
});

Why doesn't the clearInterval() works?

I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}
You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});

Categories

Resources