Javascript vanilla (jquery not preferred) - javascript

I'd like to know how to take this code I found here
http://jsfiddle.net/T42jj/
var imageGallery = [
"http://placehold.it/350x150",
"http://placehold.it/350x250",
"http://placehold.it/350x350",
"http://placehold.it/350x450"
];
var imgCount = 0; var totalImgs = imageGallery.length - 1; var timer;
function next() {
timer = setInterval(function fn() {
imgCount++;
if (imgCount > totalImgs) imgCount = 0
document.getElementById("gallery").src = imageGallery[imgCount];
return fn;
}(), 500)
}
function previous() {
timer = setInterval(function fn() {
console.log('prev')
imgCount--;
if (imgCount < 0) imgCount = totalImgs;
document.getElementById("gallery").src = imageGallery[imgCount];
return fn;
}(), 100)
}
function stopInterval() {
clearInterval(timer)
}
window.onmouseup = stopInterval;
and changing the "onMousedown" to onmouseOver so it continuously loops as you mouse over, which I've managed to do.
Then adding a stop function button that works
onmouseClick
Back
Stop
with a Stop function breaking the loop. e.g break;
sorry i cant figure out how to format any of this. this is the worst system ever.
does this [code] work? [/code]
or something like it?
basically look at the jsfiddle code and help me if you could make a function that stops the loop from infinitely repeating images when a mouse click event occurs.

Related

can i use again a function that wraps setInterval and clearInterval statements?

i have a following function:
const catchingEggs = () => {
let eggIndex;
document.querySelector('html').style.backgroundColor = 'transparent';
leftArrow.style.display = 'none';
rightArrow.style.display = 'none';
player.removeEventListener('click', catchingEggs);
leftArrow.removeEventListener('click', choosePlayerLeft);
rightArrow.removeEventListener('click', choosePlayerRight);
document.querySelector('html').requestFullscreen();
myInterval = setInterval(function(){
if(score % 10 === 0) {
speed -= 10;
intervalScore += 5
}
if(heartIndex < 0) {
clearInterval(myInterval);
return;
}
eggIndex = Math.floor(Math.random()*4);
fallingEggs(allEggs[eggIndex], speed);
}, intervalLength);
}
which works fine, but if i want to keep reusing this function after clearInterval happened, by adding another catchingEggs() to the main function:
const playGame = () => {
screen.orientation.lock('landscape');
document.querySelector('html').style.backgroundColor = 'rgb(31, 28, 28)';
playerImages[0].style.display = 'block';
player.addEventListener('click', catchingEggs);
rightArrow.addEventListener('click', choosePlayerRight);
leftArrow.addEventListener('click', choosePlayerLeft);
}
to execute after a conditional, it doesn't do anything. Ideally i'd like to be able to change intervalLength while inside the interval, but that doesn't seem to be possible, so at least i want to be able to go around it by initiating the whole thing again, for example when score >= 20, so i added a new variable when true, as a condition of clearInterval (so far so good), and then inside playGame(): if new variable true catchingEggs(), but nothing happened.
thanks in advance.

setInterval doesnt tigger inner script on first time run

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

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 )
}

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/

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories