setInterval doesnt tigger inner script on first time run - javascript

Maybe I'm not properly understanding setInterval but I have made a kind of slideshow script, as below:
var i = 0;
setInterval(function() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
if(i == 5){
i = 0;
}
}, 4000);
This works, except for the first run - no slides will display for the first 4 seconds.
See Fiddle here: http://jsfiddle.net/vpa89snf/6/
Is there anyway I can trigger whats inside the setInterval function when it runs the first time round?

Use setTimeOut instead of setInterval for better performance, inspect the sample below:
Here is working jsFiddle.
var i = -1;
var totalSlide = $('.slide').length-1;
var slideTimer = 0;
function nextFrame() {
i == totalSlide ? i = -1 : i;
i++;
$('.slide').fadeOut(200);
$('.slide').eq(i).fadeIn(200);
slideTimer = setTimeout(nextFrame,4000);
}
$('#holder').addClass('isAni');
nextFrame();
// play / pause animation
$('#holder').click(function() {
if ( $(this).hasClass('isAni') ) {
$(this).removeClass('isAni');
clearTimeout(slideTimer);
}else{
$(this).addClass('isAni');
nextFrame();
}
});

You need to run the function and not wait for the 4 first seconds:
var i = 0;
function doSomething() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i = (i + 1) % 5;
}
$document.ready(function () {
setInterval(doSomething, 4000);
doSomething(); // run it!
});
JSFIDDLE.

This is how setInterval is executed. It runs your function after x milliseconds set as 2nd parameter.
What you have to do in order to show the first slide is to have the 1rst slide fadein like below:
var i = 0;
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
setInterval(function() {
...
}, 4000);

Related

SetInterval running even after i clear it

Im having a little trouble fixing a problem i have with setInterval.
I have a function that runs when i click an element on my website that sets var pass = 1;
if you look in color1(); there is a set Interval that clears itself when pass > 0; so if pass = 1; then it should clear itself, it does, but only after running the interval one more time.
so it - runs setInterval, clears setInterval, then runs the rest of the code in setInterval. What i need, is for setInterval to clear without running the code again.
Thanks in advance
function color1() {
var pass = 1;
var counter = 2;
var animationSpeed = 800;
var $colorContent = '.color-container-1 .color-content-container'
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 3000);
}
It should be like below, you should return the function. Here you have cleared the interval but you haven't stopped the execution
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
return; //stop here so that it doesn't continue to execute below code
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 3000);

my jquery slider is running well but there is bug that it sometimes does'nt shows images on next or prev click

Found solution for the playing and stopping the slider.But problem is now with my next and prev links .these links some times does not shows any image.
my code is on the
http://jsfiddle.net/yogesh84/ftkLd/12/
var slides;
var cnt;
var amount;
var i;
var x;
var timer;
slides = jQuery('#my_slider').children();
cnt = jQuery('#counter');
amount = slides.length;
i=amount;
cnt.text(i+' / '+amount);
function run_prev() {
jQuery(slides[i]).fadeOut(1000);
i--;
if (i <= 0) i = amount;
jQuery(slides[i]).fadeIn(1000);
// updating counter
cnt.text(i+' / '+amount);
}
x=0;
function run_next() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
cnt.text(x+1+' / '+amount);
}
/***********start and stop functions***************/
function run() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
timer = setTimeout(run,2000);
}
function MySlider() {
timer = setTimeout(run,2000);
}
function stoper() {
clearTimeout(timer);
}
/***********end start and stop functions***************/
function slide_show(){
var timer;
if(jQuery('#slide_show').html()=='Play Slideshow')
{
jQuery('#slide_show').html('Stop Slideshow');
MySlider();
}
else
{
jQuery('#slide_show').html('Play Slideshow');
stoper()
}
}
// custom initialization
jQuery('#prev2').on("click",run_prev);
jQuery('#next2').on("click",run_next);
jQuery('#slide_show').on("click",slide_show);
I think you forgot to set timer
You declare at the top: timer but it is never filled.
So i think you should do:
timer = setTimeout( run, inetrval );
Also take the function outside of Run()
function run() {
}
if ( inetrval > 0 ) {
alert( inetrval );
run();
timer = SetTimeOut( run, inetrval )
}

how to replace a value in a division for every 5 seconds in jquery?

I want to replace a value in a div with id show_num_val with new value for every 5 seconds. For that I have written the following.
<div id="show_num_val"> 0 </div>
In the script:
<script>
$(document).ready(function() {
for(i=0;i<20;i++){
showThis(i);
}
});
function showThis(x) {
setTimeout(function() {
$('#show_num_val').html(x);
}, 5000);
}
</script>
But I am getting the last value i.e 20 only in the show_num_val div.
can anybody help?
You can use setInterval() if you want repetitive execution.
Live Demo
$(document).ready(function() {  
x = 1;
inverval = setInterval(function() {
$('#show_num_val').html(x++);
if(x == 21)
clearInterval(inverval);
}, 2000);​
});
var x = 0;
T = setInterval(function() {
if (x == 20) clearInterval(T);
$('#show_num_val').html(x);
x++;
}, 5000);
See it working http://jsbin.com/ajekeq/2/watch
<script>
$(document).ready(function() {
for(i=1; i<20; i++){
showThis(i, 5000 * i));
}
});
function showThis(x, y) {
setTimeout(function() {
$('#show_num_val').html(x);
}, y);
}
</script>
The reason why your code was not working because all the timers were getting over at the same time. I would have liked to use setInterval though as we are starting 20 timers at the same time. Another model is to start next timer in the setTimeout call till you are done.

Jquery: Infinite loop and pause

I have this code
var timeout = 0;
$('#container td').each(function(){
var td = this;
setTimeout(function() {
var new_text = $(td).find(text).html();
popup_text.html(new_text);
popup.fadeIn('fast').delay(1000).fadeOut('slow');
}, timeout);
timeout += 1000 + 1000;
});
I get text from table cells and is displayed in the layer with a delay.
1 question: How do I make this code to run in an endless loop?
2 question: How to do that when you hover the mouse over popop cycle temporarily stopped and then continue?
Thanks a lot!
One way is to put the code to be repeated in a function, and have the function repeat itself at the end:
var timeout = 1000;
var action = function() {
// Do stuff here
setTimeout(action, timeout);
};
action();
However, as ahren suggested, setInterval might be better:
var timeout = 1000;
var action = function() {
// Do stuff here
};
setInterval(action, timeout);
The difference is slight, but if the machine is running slowly for some reason, the setInterval version will run the code every second on average, whereas the setTimeout version will run the code once each second at most.
Neither of those methods really work well with each(), however, so you'll need to store the sequence of popups somewhere and step through them:
var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
var td = tds[index];
var new_text = $(td).html();
popup.html(new_text);
popup.fadeIn('fast').delay(1000).fadeOut('slow');
if(++index >= tds.length)
index = 0;
};
setInterval(action, timeout);
action();
Finally, to avoid moving to the next popup while the popup is hovered, you can add a check for that at the start of the function. It's also necessary to rearrange the animations so that they go "check for hover - fade out - change text - fade in".
var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
if(popup.is(':hover'))
return;
var td = tds[index];
var new_text = $(td).html();
popup.fadeOut('slow', function() {
popup.html(new_text);
}).fadeIn('fast');
if(++index >= tds.length)
index = 0;
};
setInterval(action, timeout);
action();
jsFiddle: http://jsfiddle.net/qWkYE/2/
If you like the short clean way, then use the jquery-timing plugin and write:
$.fn.waitNoHover = function(){
return this.is(':hover') ? this.wait('mouseleave') : this;
};
$('#popups div').repeat().each($).fadeIn('fast',$)
.wait(200).waitNoHover().fadeOut('slow',$).all()
​
See this on http://jsfiddle.net/creativecouple/fPQdU/3/

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories