I am trying to stop a loop so other things can run, then return to the loop again at the correct time in the sequence. The code I have runs once, but then seems to be unable to run after I use clearInterval();
function runPlanner() {
var plannerInterval = setInterval(function(){
imageCounter++;
var imageTotal = $('li img').length;
if (imageCounter > imageTotal + 1) {
$('li img').hide();
imageCounter = 0;
clearInterval(plannerInterval);
} else {
$('li img:nth-child(' + imageCounter +')').fadeIn('slow');
}
console.log('image counter:',imageCounter);
console.log('image total:',imageTotal);
}, 2500);
}
Then I can run this initially, with:
runPlanner();
But if the condition is met, where clearInterval is called, then using that function call doesn't work. Any ideas, please!?
Try to use setTimeout style. so you will not have a problem with clearInterval anymore.
like this.
function runPlanner() {
imageCounter++;
var imageTotal = $('li img').length;
if (imageCounter > imageTotal + 1) {
$('li img').hide();
imageCounter = 0;
} else {
$('li img:nth-child(' + imageCounter +')').fadeIn('slow');
// re-called `runPlanner` after 2500 sec
setTimeout(runPlanner, 2500);
}
console.log('image counter:',imageCounter);
console.log('image total:',imageTotal);
}
runPlanner();
Related
I don't know what's wrong with my code. I cannot pass a function in my javascript, [i don't want to put it inline]
My problem is my prev button and next button doesn't work, I also tried to put return false on prev and next to stop refreshing the page, but it still refreshing on click.
This is my code [please also see my comments] and my codepen:
$(document).ready(function slider() {
$('#img1').show('fade', 500);
$('#img1').delay(5000).hide("slide", { direction: 'left' }, 500);
});
var count = 2;
setInterval(function loop() {
var all = document.getElementsByTagName('li').length; // <-- i got the li elements so i did the same to prev and next
$('#img' + count).show('slide', { direction: 'right' }, 500);
$('#img' + count).delay(5500).hide('slide', { direction: 'left' }, 500);
if (count === all) {
count = 1;
} else {
count += 1;
}
}, 6500);
var sliderInt = 1;
var sliderNext = 2;
document.getElementsByClassName('prev').onclick = function prev() { // <-- not working
console.log('clicked prev');
var newSlide = sliderInt - 1;
showSlide(newSlide);
return false;
}
document.getElementsByClassName('next').onclick = function next() { // <-- not working
console.log('clicked next');
var newSlide = sliderInt + 1;
showSlide(newSlide);
return false;
}
function stopLoop() {
window.clearInterval(loop());
}
function showSlide(id) { // <-- this function doesn't work from prev and next
stopLoop(); // <-- I want to stop the loop() function when prev and next is clicked
if (id > count) {
id = 1;
} else if (id < 1) {
id = count;
}
$('li').hide('slide', { direction: 'left' }, 500);
$('#img' + id).show('slide', { direction: 'right' }, 500);
sliderInt = id;
sliderNext = id + 1;
window.slider(); // <-- I want to call the function slider here
}
a fix demo will be much appreciated :)
When you use the document.getElementsByClassName('prev').onclick you got an array. Use it like below
document.getElementsByClassName('prev')[0].onclick
document.getElementsByClassName('next')[0].onclick
getElementsByClassName returns a HTMLCollection. So you need to pass the relevant index to which you want to add the onclick function
document.getElementsByClassName('next')[0]
But this will attach the event only on the first element in the collection.
An more relevant example is
var list = document.getElementsByClassName('next or prev');
for (var i = 0, len = list.length; i < len; i++) {
(function(i){ // creating closure
list[i].addEventListener('click',function(){
// code you want to execute on click of next or prev
}
}(i))
}
As you are already using jquery you can avoid all this if you use class selector
$('.next or .prev').on('click',function(event){
// relevant code
})
How can i improve image slider transition. It is rather erratic. I want it to be smooth (smooth in and out properly). The problem is image only fadeIn, i cannot figure out how to fadeOut.
var nextimage = 0;
var timer = 0;
doSlideshow();
function doSlideshow() {
if (nextimage >= images.length) {
nextimage = 0;
}
$('.col-md-8')
.css('background-image', 'url("' + images[nextimage++][0] + '")')
.fadeIn(3000, function() {
timer = setTimeout(doSlideshow, 3000);
});
}
$(".col-md-8").hover(function() {
clearTimeout(timer);
});
$(".col-md-8").mouseout(function() {
setTimeout(doSlideshow, 3000);
});
Pen
setInterval(function(){
$("#top").fadeOut(function() {
$(this).attr("src","http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png").fadeIn().delay(1000).fadeOut(function(){
$(this).attr('src', 'http://coreldrawtips.com/images/applebig.jpg').fadeIn().delay(1000);
});
}
);
}, 400
Check this link also.
I have fixed this for you, you do not need settimeout for this kind of stuff, there are many other ways.
function doSlideshow() {
if (nextimage >= images.length) {
nextimage = 0;
}
$('.col-md-8')
.css('background-image', 'url("' + images[nextimage++][0] + '")');
$('.col-md-8').hide().fadeIn(3000).fadeOut(2000, function() {
doSlideshow()
});
}
Link to codepen, there is bit more to say about this, which I will do later.
http://codepen.io/damianocel/pen/PzQwNr
I did some searching and I'm not even sure if what I want to do is good javascript practice.
I have a while loop that I would like to exit from early if a stop button is clicked.
$( "#go" ).click(function() {
var gotime = 1;
while (gotime < 100) {
for(i = 0; i < 2; i++){
var divName = "floatName" + i;
console.log(divName);
$( "#" + divName ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, function() {
// Animation complete.
});
};
gotime += 1;
$( "stop" ).click(function() {
gotime = 101;
});
};
});
This doesn't work though. I originally had an endless loop (not incrementing gotime).
http://jsfiddle.net/cvoxe465/
Actually it stops if you wait for some time. The problem is you execute animation very often and $.animate have to queue it. There is $.stop method that allow you to stop the currently-running animation. DEMO
$( "#stop" ).click(function() {
gotime = 101;
$('#floatName0, #floatName1').stop(true, true);
});
EDIT:
Note that in the code that you provided there is mistake. Instead $("stop") you need to use $("#stop").
You may use setInterval:
Js:
var interval;
$("#go").click(function () {
var gotime = 1;
interval = setInterval(function () {
for (i = 0; i < 2; i++) {
var divName = "floatName" + i;
console.log(divName);
$("#" + divName).css({
left: Math.random() * 500 + "px",
top: Math.random() * 500 + "px"
});
};
gotime += 1;
if (gotime > 100) {
clearInterval(interval);
}
}, 500)
});
$("#stop").on('click', function () {
clearInterval(interval);
});
css:
#randomFloat {
color: red;
}
#floatName1, #floatName0 {
transition : 0.5s left, 0.5s top;
}
Fiddle
animate doesn't block the loop. The animations are stacked up and then executed, but the loop finishes a lot earlier. Here is something that works:
var loopAllowed = false;
$('#go').click(function(){
loopAllowed = true;
var max = 2;
var loop = function(){
for(var i = 0; i < max; i++){
var divName = "floatName" + i;
$( "#" + divName ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, i === max - 1 && loopAllowed ? loop : undefined);
}
};
loop();
});
$('#stop').click(function(){
loopAllowed = false;
});
JSFiddle. We manually call the loop function after the animation has ended (by passing it as the callback function). If loopAllowed is false (e.g. set to false by clicking #stop), then it won't be passed as the callback function and the looping stops.
I have a slideshow on my website but there is a problem with in.
Here, my JS:
var size_ini = 1;
$(document).ready(function() {
setInterval('$("#next").click()',10000)
$("#next").click(function() {
if(size_ini < 3);
size_ini++;
else
size_ini = 1
$(".sample").hide();
$("#id" + size_ini).show();
$(".comment" + size_ini).show();
$(".comment_description" + size_ini).show();
});
$("#prev").click(function() {
if(size_ini > 1)
size_ini--;
else
size_ini = 3;
$(".sample").hide();
$("#id" + size_ini).show();
$(".comment" + size_ini).show();
$(".comment_description" + size_ini).show();
});
});
As you can see I have a Timer of 10 sec. for slide. I have a previous and a next button. So when i clicked on one of the button the timer should stop and starts again. I have tried "clearInterval" but this doesn't work.
Can anyone tell how this works.
Here is FIDDLE.
Fiddle Demo
var size_ini = 1;
$(document).ready(function () {
var timer = setInterval('$("#next").click()', 10000); //assign timer to a variable
$("#next").click(function () {
if (size_ini < 3) size_ini++;
else size_ini = 1
$(".sample").hide();
$("#id" + size_ini).show();
clearInterval(timer); //clear interval
timer = setInterval('$("#next").click()', 10000); //start it again
});
$("#prev").click(function () {
if (size_ini > 1) size_ini--;
else size_ini = 3;
$(".sample").hide();
$("#id" + size_ini).show();
clearInterval(timer); //clear interval
timer = setInterval('$("#next").click()', 10000); //start it again
});
});
If you're going to want to clear the interval you need to assign it to a variable, then you can clear it easily -
var myInterval = setInterval('$("#next").click()',10000);
Then clear like this -
clearInterval(myInterval);
Once the interval has been cleared make sure to reset it and assign it to a variable again if you want it to continue.
<button id="start">Start</button>
<button id="stop">Stop</button>
var timer;
$("#start").click(function() {
timer = setInterval(function(){$("#next").trigger("click");},"500");
});
$("#stop").click(function() {
clearInterval(timer);
});
I'm trying to write a JS timer that will be triggered by a user click on the button with id="start".
I've got the timer itself working correctly, but when I try to add code to initiate the timer on the button click (id="start") I break it and am not sure why.
Any help would be greatly appreciated!
Here is the JS code:
$(document).ready(function(){
var count = 0;
$('#start').click(function(){
setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});
$(document).ready(function() {
$('#start').click((function(container) {
var interval;
return function() {
if(interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
})("#timer"));
});
$(document).ready(function() {
var count = 0;
var myInterval = null;
$('#start').click(function(){
myInterval = setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});
When setting your setInterval in the scope of the click handler, try assigning it to a variable to hold the interval declared up a level. This has typically always worked for me.
Not sure exactily what your objective is, but maybe you'd want to try something like this:
var startInterveal;
var timerStarted = false;
var count =0;
$(document).ready(function () {
$('#start').click(function () {
if (!timerStarted) {
timerStarted = true;
count =0;
$(this).attr('disabled', 'disabled');
startInterveal = setInterval('tick();', 1000);
}
});
});
function tick() {
count++;
$('#timer').html(count + ' tacos seconds');
}
Here is a 2nd answer if you really want to go nuts and have something resuable:
$(document).ready(function() {
$('#start').click(overboard("#timer"));
$('#start2').click(overboard("#timer2"));
});
function overboard(container) {
var interval;
return function() {
if (interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
}