loop javascript function? - javascript

Can anyone please tell me how i can add an infinite loop or a constant repeat on this piece of JavaScript I have?
<script>
$(".modcontentnewestmore").hide();
$('.morebutton').click(function () {
if ($('.modcontentnewestmore').is(":hidden")) {
$(".modcontentnewest").fadeTo(500, 0);
$('.modcontentnewestmore').fadeTo(0, 500);
} else {
$('.modcontentnewestmore').fadeTo(500, 0);
$('.modcontentnewest').fadeTo(0, 500);
}
});
</script>

I think what you should use here is setInterval. Otherwise your loop will block any other javascript you'd want to run.
JavaScript Timing Events

<script>
function doSomething{
$(".modcontentnewestmore").hide();
$('.morebutton').click(function () {
if ($('.modcontentnewestmore').is(":hidden")) {
$(".modcontentnewest").fadeTo(500, 0);
$('.modcontentnewestmore').fadeTo(0, 500);
} else {
$('.modcontentnewestmore').fadeTo(500, 0);
$('.modcontentnewest').fadeTo(0, 500);
}
});
}
setInterval(doSomething, 30); //it will loop the function doSomething every 30 ms
</script>

If you want to keep replaying some JavaScript, rather than looping use an interval or timer.
var interval = window.setInterval(function() {
console.log('hi');
}, 1000);

Infinite loop? just use following code.
while(true) {
//do something here
}

Related

How to run a function once after element has been found with Jquery/Javascript

Is there a way I can run a function once after a specific element has been found?
I tried this:
setInterval(function () {
if ($('.imagewrapper').length) {
self.carousel();
}
}, 1000)
So, it checks my page continiously if the .imagewrapper element exisit, and if so, it should run the self.carousel()function. The problem is, that this way, as soon the element exists, it runs the function continiously. Is there a way around?
ps: The setInterval-method needs to be there.
Try:
(function delay() {
if ($('.imagewrapper').length) {
self.carousel();
} else {
setTimeout(delay, 1000);
}
})();
or if you need setInterval:
var interval = setInterval(function() {
if ($('.imagewrapper').length) {
self.carousel();
clearInterval(interval);
}
}, 1000);
You looking for waitUntilExists https://gist.github.com/buu700/4200601
So, it will works something like that:
$(someselect).waitUntilExists(function(){
var that = $(this);
// do some code
})
It's easy:
// set ran to false when you load the page
ran = false;
setInterval(function () {
// only do your stuff when you haven't do yet (ran==false)
if (!ran && $('.imagewrapper').length) {
self.carousel();
// when you did it for the 1st time set ran to true, so next time you don't enter the if.
ran = true;
} }, 1000)
// but even better to stop the timer after you entered the if for the 1st time:
timer = setInterval(function () {
// only do your stuff when you haven't do yet (ran==false)
if ($('.imagewrapper').length) {
self.carousel();
// when you did it for the 1st time delete the timer
clearInterval(timer);
} }, 1000)

JQuery not executing within a For loop

Im a JQuery noob trying to write a simple jQuery code to get a text to blink three times. My initial code was as follows:
$("#welcome").click(function () {
var i = 1;
while (++i < 10) {
$("#welcome").fadeOut("slow", function () { $("#welcome").fadeIn("slow"); })();
}
});
But since I probably meddled in forces I could not comprehend, the above code made the text blink only once. I read up on closures and got convinced that the below code could make a change. Unfortunately, it doesnt.
$("#welcome").click(function () {
var i = 1;
while (++i < 10) {
(function (i) {
$("#welcome").fadeOut("slow", function () { $("#welcome").fadeIn("slow"); })();
})(i);
}
});
Can anyone tell me whats going on here?
You need make use of the animation queue
var $welcome = $("#welcome").click(function () {
var i = 1;
//clear previous animations
$welcome.stop(true, true);
while (++i < 10) {
$welcome.fadeOut("slow").fadeIn("slow");
}
});
Demo: Fiddle
Fading in and out takes some time, and you have to wait for your animation to be over before you can run the next one.
The provided answers solve your problem since jQuery is clever enough to bufferize your animation queue, but it may creates even more confusion for begginers, and also if you want to do something else between the fading animations, you can't rely on it anymore.
You then have to write your code on what is called an asynchronous recursive way (woah). Simply trying to understand that snippet may help you a lot with javascript general programming.
function blink(nbBlinks) {
// Only blink if the nbBlinks counter is not zero
if(nbBlinks > 0) {
$('#welcome').fadeOut('slow', function() {
// Do stuff after the fade out animation
$(this).fadeIn('slow', function() {
// Now we're done with that iteration, blink again
blink(nbBlinks-1);
})
});
}
}
// Launch our blinking function 10 times
blink(10);
This works perfectly. Demo http://jsfiddle.net/X5Qy3/
$("#welcome").click(function () {
for (var x = 0; x < 3; x += 1) {
$("#welcome").fadeOut("slow");
$("#welcome").fadeIn("slow");
}
});
Also, if you know how many times you want to do something. You should use a For Loop. While Loops are for when you don't know how many times you want it to run.
Set in queue
$("#welcome").click(function () {
var i = 1;
//clear animations whcih are running at that time
$(this).stop(true, true);
while (++i < 10) {
$(this).fadeOut("slow").fadeIn("slow");
}
});
You can not use jQuery delay function inside a looping/iteration hence you have to user closures:
$(document).ready(function(){
$(".click1").click(function () {
for (i=0;i<=10;i++) {
setTimeout(function(x) {
return function() {
$("#wrapper").fadeOut("slow", function () { $("#wrapper").fadeIn("slow"); })();
};
}(i), 1000*i);
}
});
});
<div id="wrapper"></div><div class="click1">click</div>
You can later change the count how many times you want to blink the <div>.

How to call a function a fixed number of times after fixed intervals in javascript

I want to call an on event function a fixed number of times and after fixed interval of time.
Example of the code which is not working
function work(i){
remove();
draw(i);
}
d3.select("body").select('button').on('click', function() {
for(var i=0;i<7;i++){
setTimeout(function(i){
remove();
draw(i);
},1500);
}
});
What is the problem with my code and please provide the solution.
All your setTimeout calls are made immediately after each other in the loop and do not wait for each other to complete. You can use setInterval to achieve the functionality you requrie:
function work(i) {
remove();
draw(i);
}
d3.select("body").select('button').on('click', function () {
work(0);
var times = 1,
myInterval = setInterval(function () {
work(times);
times++;
if (times === 7) {
clearInterval(myInterval);
}
}, 1500);
});
Try this simple soln using setTimeout
function work(i){
remove();
draw(i);
if(i<=7){//set your condition
setTimeout(function(i){
i++;
work(i);
},1500);
}
}
d3.select("body").select('button').on('click', function() {
work(0);
});
I think, using setTimeout is safer than setInterval

2 functions same time jQuery slideUp -slideDown + resize

What's the best solution to run those functions at the same time?
Mainly: slideDown and fancybox.resize, as it's now run on function complete, function fancybox.resize has to be run while slidedown is running, otherwise it won't work.
function DisplayLogin() {
jQuery("#sign-up-select").slideUp(400);
jQuery("#login-select").slideDown(400, function(){
jQuery.fancybox.resize()
});
}
Thanks!!
Adam
Thanks for help guys!!
That's what I wanted to get - final result:
function DisplayLogin() {
jQuery("#sign-up-select").slideUp(400);
jQuery("#login-select").slideDown(400);
var interval = setInterval(function(){jQuery.fancybox.resize()}, 100);
setTimeout(function() {
clearInterval(interval);
}, 400);
}
Run another function while other is 'running' using setInterval.
function DisplayLogin() {
jQuery("#sign-up-select").slideUp(400);
jQuery("#login-select").slideDown(400);
var interval = setInterval(function(){jQuery.fancybox.resize()}, 100);
setTimeout(function() {
clearInterval(interval);
}, 400);
}

Repeat code every x seconds but not if [insert check here]

This is a followup to this question, where I found out how to make code be repeated every x seconds. Is it possible to make an event that can change this? I.e. I have a checkbox which is meant to control whether this is repeated or not, so I figured I'd need something like this:
$(checkbox).bind("change", function() {
switch(whether if it is ticked or not) {
case [ticked]:
// Make the code repeat, while preserving the ability to stop it repeating
case [unticked]:
// Make the code stop repeating, while preserving the ability to start again
}
});
I have no idea what I could put in the cases.
You can do it by assigning your setInterval function to a variable.
var interval = setInterval(function() { }, 1000);
and then you can stop setInterval by
clearInterval(interval);
p.s.
to start your interval you need to call var interval = setInterval(function() { }, 1000); again
You can either stop and start the interval:
var timer;
function start() {
timer = window.setInterval(function(){
// do something
}, 1000);
}
function stop() {
window.clearInterval(timer);
}
start();
$(checkbox).bind("change", function() {
if ($(this).is(':checked')) {
start();
} else {
stop();
}
});
Or you can have a flag causing the interval to skip the code:
var enabled = true;
var timer = window.setInterval(function(){
if (!enabled) {
// do something
}
}, 1000);
$(checkbox).bind("change", function() {
enabled = $(this).is(':checked');
});
function fooFunc() {
$('#foo').text(+new Date());
}
var id;
var shouldBeStopped = false;
$('input').change(function() {
if (shouldBeStopped)
clearInterval(id);
else
id = setInterval(fooFunc, 200);
shouldBeStopped = !shouldBeStopped;
});​
Live DEMO

Categories