jQuery/JavaScript timer - javascript

I have a simple function that I wrote that transitions three div elements using a fade in/out effect. The event is triggered when a user clicks a link. Here's my code:
$(".link1").click(function () {
$(".feature1").fadeIn(1000);
$(".feature2").fadeOut(1000);
$(".feature3").fadeOut(1000);
});
$(".link2").click(function () {
$(".feature1").fadeOut(1000);
$(".feature2").fadeIn(1000);
$(".feature3").fadeOut(1000);
});
$(".link3").click(function () {
$(".feature1").fadeOut(1000);
$(".feature2").fadeOut(1000);
$(".feature3").fadeIn(1000);
});
I need to be able to set some sort of timer so that these transitions happen automatically every 8 seconds or so. I also want them to "loop" essentially, so that if we get to the third div in the set, it returns to the first div.

Try using setTimeout() function.
var timer = null;
function foo_loop(div, timeout) {
if (div > 3) div = 1;
$(".feature"+div).fadeIn(1000);
$("div[class^=feature]:not(.feature"+div+")").fadeOut(1000);
clearTimeout(timer);
timer = setTimeout(function() {
foo_loop(div + 1, timeout);
}, timeout);
}
Run this like that (To start with first div and 8 second timeout):
foo_loop(1, 8000);
Function for stopping loop:
function stop_loop() {
clearTimeout(timer);
}
Run it when you need to stop the loop (for example on click on element with id="stop"):
$('#stop').bind('click', stop_loop);

setInterval(expression, timeout); runs the function in intervals, with the length of the timeout between them
example:
var intervalID = setInterval(alert('heelo'), 3000); // will alert hello every 3 seconds
// clearInterval(intervalID); // will clear the timer

Try the following:
var i = 0;
var transition = setInterval(function(){
i++;
if (i == 4) {i = 1}
$(".feature"+i).stop().fadeIn(1000, function(){
$(this).delay('6000').fadeOut(1000)
})
}, 8000)

not sure I fully understand when you want them to loop or how often, but I think this should help you out a bit... every 8 seconds it loops through the animations...
function fadeLoop(selectors, animations, times, index) {
index = index || 0;
if(index == selectors.length) return;
$((selectors[index])[animations[index]](times[index], function() {
fadeLoop(selectors, animations, times, index + 1);
});
}
setInterval(function() {
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeIn', 'fadeOut', 'fadeOut'],
[1000, 1000, 1000]
);
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeOut', 'fadeIn', 'fadeOut'],
[1000, 1000, 1000]
);
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeOut', 'fadeOut', 'fadeIn'],
[1000, 1000, 1000]
);
}, 1000 * 8);

Related

How to set interval only on entering specific section with scroll and clear it immediately?

There is this code below, which is pretty straightforward:
User scrolls into some section and that section is flagged with a CSS class "view"
When I get to that specific section "someClsOfSection" I want to trigger adding 20 different classes to some element with setInterval
Whenever I scroll the condition will be fulfilled and I don't know how to clear the interval once I enter this section...
https://codepen.io/StevaNNN/pen/GRNOLyJ here is the codepen for
const isFullySeen = el =>
el && typeof el.getBoundingClientRect === 'function'
&& el.getBoundingClientRect()['top'] +
window.scrollY + (window.innerHeight) <= window.innerHeight + window.scrollY;
$(document).ready(function () {
$(window).scroll(function () {
$('.section').each(function() {
if (isFullySeen(this) === true) {
$(this).addClass('in-view');
}
if(isFullySeen(this) && $(this).hasClass('.someClsOfSection')) {
let tempCls = 0;
let toTwentyPercent = setTimeout(function () {
setInterval(function () {
if (tempCls < 20) {
tempCls++;
$('.c100').addClass(`p${tempCls}`).animate();
}
}, 100);
}, 1000);
clearInterval(toTwentyPercent);
}
});
});
});
Actually, the setTimeout() is assigned to toTwentyPercent... But is cleared right after. So it never execute its callback. Additionnaly, it's the setInterval() that you wish to clear. So here is what I suggest you to try:
let tempCls = 0;
setTimeout(function () {
let toTwentyPercent = setInterval(function () {
if (tempCls < 20) {
$('.c100').eq(tempCls).addClass(`p${tempCls}`);
tempCls++;
}else{
clearInterval(toTwentyPercent);
}
}, 100);
}, 1000);
So here, the script will wait 1 second, then will assign a setInterval() to toTwentyPercent.
Then, every 100 ms, a class will be added to a .c100 element. Notice the .eq(tempCls) to add the p0, p1, p2... in sequence. Without the .eq() method, all .c100 element will get an added class on each interval... And on the last interval, they will all have the classes from p0 to p19.
Finally, when tempCls < 20 is false, that is the time to clear the interval.
I removed the .animate() because I don't know what is the intend. That method need at least one property to animate to a new value. It is pretty useles without any argument.

stop javascript loop, setTimeout

This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.
I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.
setTimeout(function() {
createSnow(20);
loop();
}, 10000)
here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW
You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ
I added a variable to indicate if animation should be happening:
var animating = true;
A routine to stop the animation:
function stopAnimation() {
animating = false;
//Add something in here to clear the screen
}
A validation check in the animation loop:
function loop() {
if (animating) {
draw();
update();
animFrame(loop);
}
}
And changed your timeout to turn off the animation:
createSnow(150);
loop();
setTimeout(stopAnimation, 10000);
Cool animation!!
What you'll want to do is create a "timer", finding the difference between when you started and the current time.
I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.
createSnow(20);
const start = new Date();
while(new Date() - start < 10000) {
loop();
}
Use cancelAnimationFrame.
Sample usage
Declare cancelAnimFrame:
var cancelAnimFrame =
window.cancelAnimationFrame ||
window.mozcancelAnimationFrame ||
window.webkitcancelAnimationFrame ||
window.mscancelAnimationFrame;
Update loop function:
var animId;
function loop() {
draw();
update();
animId = animFrame(loop);
}
and use animId to stop animation.
(As already mentioned, starting snowing should be out of setTimeout.)
createSnow(20);
loop();
setTimeout(function() {
cancelAnimFrame(animId)
}, 1000)
the only thing that you have to change is a little change of your code plz see this code below :
var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);
clearTimeout(timeOut);

Individual slide delay // Superslides

This is a problem with superslides from nicinabox Github Link
I know that you can use the 'play' option in order to set a time in milliseconds before progressing to the next slide automatically. This sets a global time for the entire slideshow.
What I would like to achieve is for individual slides to have their own specific progress/delay time.
For example if I have a slideshow with twenty slides I want all the slides to progress automatically and to stay on screen for 5 seconds. However the third slide should be displayed for 20 seconds.
I have tried to do this by using the animated.slides event but I cant get it to work as the animation stops with the fourth slide :
Here is my code:
$(function () {
$('#slides').superslides({
hashchange: true,
play: 5000,
pagination: true
});
});
$('#slides').on('animated.slides', function () {
var current_index = $(this).superslides('current');
if (current_index === 2) { // third slide
$(this).superslides('stop');
var disp = function test1() {
setTimeout(function ()
{
$('#slides').superslides('animate', 3)
}, 20000);
}
disp();
}
});
Any help would be appreciated. Maybe there is someone out there to solve my problem.
Replace .superslides('animate', 3) with .superslides('start').
Demo (the condition is 2, as you originally wrote)
Just do this:
$('#slides').on('animated.slides', function () {
var current_index = $(this).superslides('current');
if (current_index === 2) { // third slide
$(this).superslides('stop');
var disp = function test1() {
setTimeout(function ()
{
$('#slides').superslides('start')
}, 20000);
}
disp();
}
});
FIDDLE
You can do it like this:
$('#slides').superslides({
hashchange: true,
play: 500,
pagination: true
});
$('#slides').on('animated.slides', function () {
var slideNo = $(this).superslides('current');
if(slideNo === 2){
$(this).superslides('stop');
setTimeout(function(){
$('#slides').superslides('start')
}, 2000);
}
});
Here's a fiddle.

jQuery Fade object after 20 seconds of inactivity

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.
I have the following code:
if($('.main-popup2').is(":visible")){
setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
Problem is I don't know how to reset the setTimeout after detecting a user mouse click.
Thanks!
The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.
Here is an example of how to use this:
var timer;
if($('.main-popup2').is(":visible")){
// create the timer and save its reference
timer = setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
// when clicking somewhere on the page, stop the timer
$(document).click(function() {
clearTimeout(timer);
}):
var timeout = null;
var fadeElement = $('.main-popup2');
function fader() {
if(null !== timeout) {
clearTimeout(timeout);
}
fadeElement.stop();
timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000);
}
$(document).click(fader);
fader();
Use delay function.
(window).click(function () {
$('.main-popup2').delay(6000).fadeOut(300);
}
Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

jquery blink a few

i want to give blink effect to an element by using addClass and removeClass 3 times each
i tried this
$("#div").addClass("orange").delay(300).queue(function(next){
$(this).removeClass("orange");
next();
});
this is works just 1 time
how can i make this happened 3 times with 300 ms delay?
Just count to three:
(function() {
var count = 0, $div = $('#div'), interval = setInterval(function() {
if ($div.hasClass('orange')) {
$div.removeClass('orange'); ++count;
}
else
$div.addClass('orange');
if (count === 3) clearInterval(interval);
}, 300);
})();
You could get fancy and write your own animation plugin for it, I guess.

Categories

Resources