Successive setTimout() calls all execute at once - javascript

setTimeout(thisFunc, 500);
setTimeout(thatFunc, 500);
setTimeout(otherFunc, 500);
finalFunc();
What I expect is thisFunc(), followed by a half second pause, then thatFunc() followed by a half second pause, then otherFunc(), followed by a pause. Then finalFunc().
What actually happens, is the page pauses for 1 1/2 seconds then all four functions seem to execute at once.
How can I achieve the pause I am after? It's being done purely for aesthetical purposes in the UI.

You can use the callbacks too if you need to use 500 ms as a variable for example:
var timeout = 500;
setTimeout(function() {
thisFunc();
setTimeout(function() {
thatFunc();
setTimeout(function() {
otherFunc();
}, timeout);
}, timeout);
}, timeout);

An alternate way would be:
setTimeout(thisFunc, 500);
function thisFunc () {
/* ...whatever... */
setTimeout(thatFunc, 500);
}
function thatFunc () {
/* ...whatever... */
setTimeout(otherFunc, 500);
}
function otherFunc () {
/* ...whatever... */
setTimeout(finalFunc, 500);
}
function finalFunc () {
/* ...whatever... */
}

Try to give the delay properly,
setTimeout(thisFunc, 500);
setTimeout(thatFunc, 1000);
setTimeout(otherFunc, 1500);
setTimeout(finalFunc, 2000);
If you give 500 ms for all the setTimeouts, then every thing would be fired at a same time.
And the best approach would be,
var func = function(func){ func(); }
function setContinuos() {
var funcs = Array.from(arguments);
var delay = funcs.pop();
funcs.forEach(function(itm, index) {
setTimeout(function() {
func(itm);
}, (index + 1) * delay)
});
}
setContinuos(func1,func2,func3,func4,500);
DEMO

Related

How can I stop custom jQuery function which is running?

I have a custom jQuery function. When it runs every 5 seconds.
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
I have a
clearInterval(interval);
to stop, but I also want to stop the function completely. How can I do that ?
Functions you add to this object will be attached to your object and Simple and naive solution will follow:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
to stop use
var feature = $("#container").mycustomfunction();
feature.stop();

setTimeout() not working in return value

I have add setTimeout but it's not working. I want to show question after 5 sec of the end of the sound.
self.getQuestionText = function() {
startSound('levelq', false);
setTimeout(function() {
return self.questions[self.level() - 1].question;}, 5000);
}
setTimeout() in asynchronous and returns the value in the callback function. Change the structure of your js.
Instead of:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
return self.questions[self.level() - 1].question;
}, 5000);
}
// The rest of the code
Use callback structure:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
self.getQuestionText = self.questions[self.level() - 1].question;
// The rest of the code
}, 5000);
}

Jquery loop and run the (click) functions each X seconds

I have this (simplified for here) code which change the background position on click,
but i need to put them in a auto loop too
<script type="text/javascript">
$(window).load(function(){
$(".sle1").click(function() {
$(".slimgs").animate({backgroundPosition: '-908px 0px'});
});
$(".sle2").click(function() {
$(".slimgs").animate({backgroundPosition: '-681px 0px'});
});
$(".sle3").click(function() {
$(".slimgs").animate({backgroundPosition: '-454px 0px'});
});
});
</script>
I mean after 5 seconds of page load this first function runs
$(".sle1").click(function() {
$(".slimgs").animate({backgroundPosition: '-908px 0px'});
});
then after 5 second the .sle2 and when it reachs the .sle3 (last function) after 5 seconds it should go back and run the first function again (a loop)
i tried putting ", 5000)" after each function but it didn't work
any help is appreciated
Use window.setInterval to execute a function every 5 seconds.
To cycle through those three functions, you could store all of them in an array and set i every time to the function that should be called next.
var i = 0;
var functions = [
function() {
// instead of copying that code, you could also do
// $(".sle1").click() - or you can just use functions[0]
// as argument when assigning the click listener.
$(".slimgs").animate({backgroundPosition: '-908px 0px'});
i = 1;
},
function() {
// second animation here
i = 2
},
function() {
// third animation here
i = 0
}
];
window.setInterval(function () {
functions[i]();
}, 5000);
[Edit]: no more ring-counter as that wouldn't work with the clicking.
For future reference: If you don't need the clicking to interfere with the automatic switching and want to archive something similar with only automatic cycling, get rid of th i= statements in the functions and instead insert i++; i%= functions.length after functions[i]();.
This should work, altough there are more ellegant ways to do it
$(window).load(function(){
$(".sle1").click(function() {
$(".slimgs").animate({backgroundPosition: '-908px 0px'});
window.setTimeout(function() {
$(".sle2").click();
},5000);
});
$(".sle2").click(function() {
$(".slimgs").animate({backgroundPosition: '-681px 0px'});
window.setTimeout(function() {
$(".sle3").click();
},5000);
});
$(".sle3").click(function() {
$(".slimgs").animate({backgroundPosition: '-454px 0px'});
window.setTimeout(function() {
$(".sle1").click();
},5000);
});
window.setTimeout(function() {
$(".sle1").click();
},5000);
});
setTimeout(
function() {
$(".sle1").trigger('click');
setInterval(
function() {
$(".sle1").trigger('click');
},
15000
);
},
5000
);
setTimeout(
function() {
$(".sle2").trigger('click');
setInterval(
function() {
$(".sle2").trigger('click');
},
15000
);
},
10000
);
setTimeout(
function() {
$(".sle3").trigger('click');
setInterval(
function() {
$(".sle3").trigger('click');
},
15000
);
},
15000
);
In case you're willing to improve your code, making it more concise, you could try the following, using window.setInterval:
function changeBackground(interval, frames) {
var int = 1;
function changer() {
document.body.id = "b" + int;
int++;
if (int === frames) {
int = 1;
}
}
var swap = window.setInterval(changer, interval);
}
changeBackground(2000, 10); //milliseconds, frames
Example online
Talking about your example, it's harder to tell as it's not very clear.
Try adding .stop() and duration for your .animate() effects:
$(window).load(function(){
$(".sle1").click(function() {
$(".slimgs").stop().animate({backgroundPosition: '-908px 0px'}, 5000);
});
$(".sle2").click(function() {
$(".slimgs").stop().animate({backgroundPosition: '-681px 0px'}, 5000;
});
$(".sle3").click(function() {
$(".slimgs").stop().animate({backgroundPosition: '-454px 0px'}, 5000);
});
});
.stop() - The jQuery .stop() method is used to stop animations or effects before it is finished.

Better way to run a finite cycle of animations

First of all, this code, as ugly as it is, works, for all intents and purposes. However, it really makes me both sick and mad to look at.
For the lazy, the main portion of the code that sucks is this:
setTimeout(function() {
toggle(); //off
setTimeout(function() {
toggle(); //on
setTimeout(function() {
toggle(); //off
setTimeout(function() {
toggle(); //on, stays for stallTime
setTimeout(function() {
toggle(); //off
callback();
}, stallTime);
}, 300);
}, 300);
}, 300);
}, 300);
I would, of course, love to control my animations just by changing the CSS class on an element. However, transitionend and webkitTransitionEnd and the like are not reliable in the least. Am I forced to resorting to this kind of hideous code? Ideally I'd like to be able to set a variable number of "flashes", but this code is too stodgy for that.
Please rescue me from my filth.
var count = 5;
var i = setInterval(function() {
toggle();
count--;
if(count == 0) {
clearInterval(i);
callback();
}
}, 300);
To avoid setInterval, I wrote a recursive function:
// link.addClass('hover'); //on - no longer needed
flash = function(count) {
if (count > 1) {
setTimeout(function() {
toggle();
flash(count - 1);
}, 300);
} else {
setTimeout(function() {
toggle(); //off
callback();
}, stallTime);
}
}
flash(6); // 2 * the number of flashes.

settimeout not getting cleared

What I'm trying to do is, when the page loads a box appears after 3 seconds and if nothing happens, it gets partially hidden after 3 seconds. Now if the cursor enters the box, timeout is cleared and the ad won't be getting hidden as I'm clearing the timeout.
The problem is when the mouse leaves and enters again, the previous timeout is still there. Though I'm trying to clear the timeout but it still hides the box. What can be the problem?
See my code: (JSfiddle link: http://jsfiddle.net/aK9nB/)
var pstimer;
$(document).ready(function(){
setTimeout(function(){
showps();
pstimer = setTimeout(function() {
hideps();
}, 3000);
}, 3000);
});
$('#psclose').on('click', function(){
$('#postsearch-container').hide();
});
$("#postsearch-container").hover(
function () {
console.log("enter");
clearTimeout(pstimer);
console.log("cleartimeout");
showps();
},
function () {
console.log("leave");
clearTimeout(pstimer);
var pstimer = setTimeout(function(){
hideps();
} , 3000);
});
function showps() {
$("#postsearch-container").stop();
$('#postsearch-container').animate({
bottom: '0'
}, 'slow');
}
function hideps() {
$('#postsearch-container').animate({
bottom: '-115'
}, 'slow');
}
$("#postsearch-container").hover(
function () {
console.log("enter");
clearTimeout(pstimer);
console.log("cleartimeout");
showps();
},
function () {
console.log("leave");
clearTimeout(pstimer);
pstimer = setTimeout(function(){ // remove the "var"
hideps();
} , 3000);
}
);
try removing the var in front of pstimer.
function () {
console.log("leave");
clearTimeout(pstimer);
/* var */ pstimer = setTimeout(function(){
hideps();
} , 3000);
}
using var defines a new local-variable that shares the name with your intended pstimer, but is only available within this function call. When the function is complete, the local var is destroyed.

Categories

Resources