Can't See Why setInterval() is Being Cleared - javascript

I can't for the life of me see why my setInterval() function is only executing one time. I believe I am doing it right according to its usage. It's a slideshow script that takes a group of slides as part of a slideshow object called TheBand and changes slides using setInterval().
This is the timer:
current_band.obj_timer = window.setInterval(function () {
TheBand.nextSlide(current_band_id);
}, current_band.timer);
This is the nextSlide function:
nextSlide : function (band_id) {
var obj_band = TheBand.bands[band_id];
if (band_id == 0) {
console.log(obj_band.current_slide, obj_band.slide_count)
}
if (obj_band.current_slide + 1 >= obj_band.slide_count) {
new_slide = 0;
} else {
new_slide = obj_band.current_slide + 1;
}
TheBand.changeSlide(band_id, new_slide);
},
Then the changeSlide function:
changeSlide : function (band_id, slide_id) {
var obj_band = TheBand.bands[band_id];
if (slide_id != obj_band.current_slide) {
// Get the viewport width for display purposes
var slide_width = jQuery(obj_band.viewport).width();
// Set up the slide objects
var current_slide = jQuery(obj_band.slides[obj_band.current_slide]);
var new_slide = jQuery(obj_band.slides[slide_id]);
// Set the left value for the new slide and show it
new_slide.css('left', slide_width).width(slide_width).height(obj_band.max_height);
new_slide.show();
// Animate the slide transition
current_slide.animate({ left: -slide_width }, obj_band.transition_time);
new_slide.animate({ left: 0 }, obj_band.transition_time, 'swing');
if (new_slide.css('background-color') != current_slide.css('background-color')) {
jQuery(obj_band.back).animate({ backgroundColor : new_slide.css('background-color') }, obj_band.transition_time);
}
// Set the class for the nav buttons
jQuery(obj_band.nav_buttons[obj_band.current_slide]).removeClass('selected');
jQuery(obj_band.nav_buttons[slide_id]).addClass('selected');
// Run the slide javascript - be careful with this!
eval(obj_band.slide_script[obj_band.current_slide].unload);
eval(obj_band.slide_script[slide_id].load);
window.setTimeout(function () {
eval(obj_band.slide_script[slide_id].ready);
}, obj_band.transition_time);
// Set the current slide variable
obj_band.current_slide = slide_id;
// Set the correct Nav color
TheBand.setNavColor(band_id);
}
},
Seems simple enough, but I only get to the second slide!? No errors or warnings in console and if I watch the clear timer breakpoint it does show a clear timer event, but its not from this code... Please help?
P.S. The setInterval() timer does not break if I comment out the changeSlide function.

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.

JS - How to run something when a function has ended

Here is a code that should open and close my site's menu. The menu is divided to divs and each one is timed to enter the screen after the other.
<script type="text/javascript">
var s=0;
function menuOpen() {
if (s==0){
document.getElementById("menu_icon").src = "x.png";
document.getElementById("nav_menu").style.zIndex = "3";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.remove('loading');
}, index * 100);
});
s++;
} else {
document.getElementById("menu_icon").src = "menu_icon.png";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.add('loading');
}, index * 100);
});
s=0;
// how to make this part run after the menu has finished folding?
setTimeout(function(){
document.getElementById("nav_menu").style.zIndex = "1";
}, 1500);
}
}
</script>
The content of the page is at z-index 2. The menu when folded is at 1 and when open at 3.
Is there a way to run the command moving the menu to z-index 1 after the menu has finished folding completely?
Currently what I did was to time the animation (1600ms) and use setTimeout. But this timing will change if I'll add more lines to my menu or if someone is clicking rapidly on the menu icon.
I'm rather new to JS and Jquery so go easy on me (:
Thanks of your help.
Below you can find the code and link to jsfiddle. Unfortunetly jsfiddle blocks the animate method for unknown reason so I don't debug, but even if it code will not work :))) I hope you will cathch the idea. And also some explanation.
Firstly our items are hidden. There are two functions displayMenu and hideMenu, they are similar, but display - run animations from the top invisible, and hide - start hide items from the bottom visible. To prevent mess I use two flags and two classes, first openFlag it is say what animations should be played now. Our hide and display functions are recursive and after they end current animation(hide or show) they check openFlag, and play next hide/show or start another chain of hide/show functions. It is the most difficult to understand part) But important that with it you can click as many times as you want and all would be fine and would be never broken by clicks.
Two classes we use as animation-chain can change behaviour and we need the way to choose items that alredy visible or hidden, so this why after each animation we set only one of this classes and remove another.
Now there is one problem if all animation are ended when we click button we should start new chain of animations, but if chain has been already started we need just to switch openFlag, and when current animation stops, it will change the behaviour. So this is the reason for btnFlag it is 1 if no active chain-animations at this moment.
After the last execution of element of animation-chain it will call callback arg, that you should pass, also at this moment will set btnFlag to 0, that means that animation-chain stopped. The openFlag as you remember changed at moment og click.
function end() {
console.log("here you can set zIndex");
}
var openFlag = 0; //become 1 after we start open elems
var btnFlag = 1;
$(document).ready(function() {
$('.toggleMenu').click(function() {
if (!$('.menuBlocks').hasClass('visible')) {
if (openFlag == 0) {
openFlag = 1;
if (btnFlag) {
var items = $('.invisibleItem');
var amount = items.length;
displayMenu(0, amount, items, end);
}
}
} else {
openFlag = 0;
if (btnFlag) {
var items = $('.visibleItem');
var amount = items.length;
hideMenu(amount - 1, items, end);
}
}
});
});
function displayMenu(i, amount, items, callback) {
if (i < amount && openFlag) {
items[i].animate({
"width": "100px"
}, 1000, function() {
items[i].removeClass('invisibleItem');
items[i].addClass('visibleItem');
displayMenu(i + 1, amount, items);
});
} else if (!openFlag) {
var items = $('.visibleItem');
var amount = items.length;
hideMenu(amount - 1, items, makeToggleVisible);
} else {
btnFlag = 1; //all aniimations ended
callback();
}
}
function hideMenu(i, items, callback) {
if (i < 0 && openFlag) {
items[i].animate({
"width": "0px"
}, 1000, function() {
items[i].removeClass('visibleItem');
items[i].addClass('invisibleItem');
hideMenu(i - 1, amount, items);
});
} else if (!openFlag) {
var items = $('.invisibleItem');
var amount = items.length;
displayMenu(0, amount, items, makeToggleVisible);
} else {
btnFlag = 1; //all animations are ended
callback();
}
}
https://jsfiddle.net/ShinShil/nrtyshv5/4/
Ok fixed it.
I moved everything to jquery. Used animate and promise.
This is what came out at the end. It is a side menu that will open it's li elements one-by-one.
var s=0;
var navMenu = document.getElementById("nav_menu");
var navBtn = document.getElementById("btn");
$(document).ready(function(){
$("button").click(function(){
if (s==0) {
navMenu.style.zIndex = "4";
navBtn.classList.add('close');
$('ul').each(function() {
$(this).children().each(function(i) {
$(this).delay(i * 100).animate({left:0});
});
});
$( "li" ).promise().done(function() {
navMenu.style.zIndex = "4";
});
s++;
}
else {
navBtn.classList.remove('close');
$('ul').each(function() {
$(this).children().each(function(i) {
$(this).delay(i * 100).animate({left:"100%"});
});
});
s=0;
$( "li" ).promise().done(function() {
navMenu.style.zIndex = "1";
});
}
});
});
and with CSS transitions.
var s=0;
function menuOpen() {
if (s==0){
document.getElementById("menu_icon").src = "x.png";
document.getElementById("nav_menu").style.zIndex = "3";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.remove('loading');
}, index * 100);
});
s++;
$("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
document.getElementById("nav_menu").style.zIndex = "3";
});
} else {
document.getElementById("menu_icon").src = "menu_icon.png";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.add('loading');
}, index * 100);
});
s=0;
$("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
document.getElementById("nav_menu").style.zIndex = "1";
$("#nav_menu").scrollTop(0);
});
}
}

Javascript slider loop

I have been trying to create an image slider for html by changing the value of the image element, using a loop to go through each image and then returning to the original image.
However once it reaches the end of the loop it doesn't continue.
Here is my Js code:
window.onload = function() {
var x = 0
while(x<1000){
setTimeout(function() {
document.getElementById('carousel').src='img/header2.jpg';
setTimeout(function() {
document.getElementById('carousel').src='img/header3.jpg';
setTimeout(function() {
document.getElementById('carousel').src='img/header.jpg';
}, 5000);
}, 5000);
}, 5000);
x = x+1
}
}
I'd recommend you to not do while loop in this case. Just recall setTimeout when executed.
window.onload = function() {
/* Element */
var carousel = document.getElementById('carousel'),
/* Carousel current image */
cimage = 2,
/* Carousel source images */
csources = [
'img/header2.jpg',
'img/header3.jpg',
'img/header.jpg'
];
function changeCarouselImage() {
// Reset the current image if it's ultrapassing the length - 1
if(cimage >= 3) cimage = 0;
// Change the source image
carousel.src = csources[cimage ++];
// Re-call the function after 5s
setTimeout(changeCarouselImage, 5000);
}
setTimeout(changeCarouselImage, 5000);
};
The final function does not set another timeout, and thus the animation does not continue. Seperating into individual functions should help:
var carousel = document.getElementById('carousel');
function ani1() {
carousel.src = 'img/header.jpg';
window.setTimeout(ani2, 500);
}
function ani2() {
carousel.src = 'img/header2.jpg';
window.setTimeout(ani3, 500);
}
function ani3() {
carousel.src = 'img/header3.jpg';
window.setTimeout(ani1, 500);
}
window.onload = ani1;

Javascript Text Slideshow Start from Beginning on Hover

I have added a text slideshow to a div that is called by JQuery on hover. How do I get the slideshow to start from the beginning each time the user hovers on the div? Right now it just continues to loop after the first time it is activated.
Thanks in advance!
<script>
$(document).ready(function(){
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
};
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
setInterval(function() {
$("#lstextslide").html(quotes[i]);
if (i == quotes.length)
i=0;
else
i++;
}, 1 * 4000);
});
});
</script>
You have to cancel the previous interval and call the function that updates the HTML immediately. See http://jsfiddle.net/xozL96fj/
$(document).ready(function(){
var intervalTimer = null;
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
}
if (intervalTimer !== null) {
clearInterval(intervalTimer);
}
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
function update() {
$("#lstextslide").html(quotes[i]);
i = (i + 1) % quotes.length;
}
// Call it immediately, don't wait until the interval
update();
intervalTimer = setInterval(update, 4000);
});
});
You need to make a check if your slider has already been activated. If you hover over your slider when the slider is already active, you will have to reset $i, and call setInterval() again.

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.

Categories

Resources