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

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.

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();

Successive setTimout() calls all execute at once

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

Run a function after each function

For some reason, I can't get a function to run after the each function is complete. This is what I tried and the each function works perfectly but it does not run the other function when it is complete.
var delay = 0;
$('h1 span').each(function() {
var $span = $(this);
setTimeout(function() { $span.addClass('visible'); }, delay+=1000, function(){
$('header').addClass('visible');
});
});
If i understand your expected behaviour, you can use following logic inside delayed function:
var delay = 0;
$('h1 span').each(function () {
var $span = $(this);
setTimeout(function () {
$span.addClass('visible');
// if $span is last of 'h1 span' matched set
if ($span.is($('h1 span').last())) {
$('header').addClass('visible');
}
}, delay += 1000);
});
-DEMO-
I think what you want to do is this http://jsfiddle.net/gon250/8mdodywe/
setTimeout() function doesn't support two callbacks.
$.when($('span').each(function() {
$(this).addClass('visible');
})).then(function(){
$('header').addClass('visible');
});
I guess that's what you want:
var delay = 0;
$('h1 span').each(function() {
var $span = $(this);
setTimeout(function() { $span.addClass('visible'); }, delay+=1000);
});
setTimeout(function() { $('header').addClass('visible'); }, delay);
Check it out: http://jsfiddle.net/zsm4xegr/
I'm assuming, you want two timeouts? From your Code it seems you would like to execute the first timeout after "delay 0". In that case simply execute the first "callback" and set a timout for the second.
If you do indeed want two timeouts (each after 1000ms):
$('h1 span').each(function() {
var $span = $(this);
setTimeout(
function() {
$span.addClass('visible');
setTimeout(
function() {
$('header').addClass('visible');
},
1000
);
},
1000
);
});

why setTimeout() only run my code once,at first time? [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
i use this javascript code to open two pictures and toggle a vertical menu by clicking on another picture. an know i want to run code without clicking on image, with a timer. so i wrote this code but it run only once at first time.
what's wrong with my code?
<script type="text/javascript">
$(document).ready(function () {
$("#lista2").slideToggle(1);
$curtainopen = false;
$(".rope").click(function () {
$(this).blur();
if ($curtainopen == false) {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-on.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
$(".rightcurtain").stop().animate({ left: '120px' }, 2000);
$("#R").attr('src', 'images/Right.gif');
$("#L").attr('src', 'images/Left.gif');
$curtainopen = true;
$("#lista2").slideToggle(2000);
$(this).attr('id', '1');
} else {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-off.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '0px' }, 2000);
$(".rightcurtain").stop().animate({ left: '0px' }, 2000);
$curtainopen = false;
$("#lista2").hide();
$(this).attr('id', '0');
}
return false;
});
});
function startTimer() {
setTimeout($(".rope").click(), 4000);
}
</script>
use this to execute your code after a specific time interval
setInterval(function() {
$(".rope").click(); // this will execute after every 4 sec.
}, 4000);
use this to execute your code after a specific time delay
setTimeout(function() {
$(".rope").click(); // this will execute after 4 sec delay only once.
}, 4000);
use above according to your requirement
setTimeout need a function, When you are passing $(".rope").click() it is called immediately.
Use it like
function startTimer() {
setTimeout(function () {
$(".rope").click();
}, 4000);
}
setTimeout(function() {
$(".rope").click();
}, 4000);
because setTimeout needs a function, but $(".rope").click() calls itself immediatly (instead of assigning a function to be called). So you don't want to call a function but to pass it to setTimeout.
A timer implies repeating the function after each timeout. setTimeOut only delays a function once (after a given time, in milliseconds).
function startTimer() {
//do your stuff
$(".rope").click();
//repeats itself after 4 seconds
setTimeout(startTimer, 4000);
}
And do not forget to start it on document ready :
$(document).ready(function () {
startTimer();
...
}
I you don't want your function to be called immediately on page load, you can add an initial delay :
$(document).ready(function () {
setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
...
}

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