jQuery setTimeout wait - javascript

I have a simple JS function, to animate this form progress Bar:
https://codepen.io/himanshu/pen/syLAh
This is how my function looks like now:
function makeAnimate() {
var i = 1;
$('.progress .circle').removeClass().addClass('circle');
$('.progress .bar').removeClass().addClass('bar');
setInterval(function() {
$('.progress .circle:nth-of-type(' + i + ')').addClass('active');
$('.progress .circle:nth-of-type(' + (i-1) + ')').removeClass('active').addClass('done');
$('.progress .circle:nth-of-type(' + (i-1) + ') .label').html('✓');
$('.progress .bar:nth-of-type(' + (i-1) + ')').addClass('active');
$('.progress .bar:nth-of-type(' + (i-2) + ')').removeClass('active').addClass('done');
i++;
if (i==0) {
$('.progress .bar').removeClass().addClass('bar');
$('.progress div.circle').removeClass().addClass('circle');
i = 1;
}
//Here i would do if i equal 3 wait in the loop extra 100ms
if (i == 1) {
setTimeout(function(){
}, 100);
}
//Here i would do if i equal 3 wait in the loop extra 200ms
if (i == 3) {
setTimeout(function(){
}, 200);
}
}, 800);
}
It's not working. How can I do that to wait exrta millisecs?
Thank you!

What you need is extract the animation function and pass it to interval, save the interval as a scoped variable so you can clear it and assign new value with different timeout.
Here is a working proof of concept:
$(function() {
var i = 0;
var timeout = 1000; // 1 Second
$('.timeout').text(timeout);
$('.i').text(i);
var animate = function() {
if (i === 2) {
timeout = 6000; // 6 Seconds
clearInterval(interval);
interval = setInterval(animate, timeout);
}
if (i === 3) {
timeout = 1000; // Back to 1 second
clearInterval(interval);
interval = setInterval(animate, timeout);
}
if (i >= 7) {
// Remember to clear the interval once your steps complete, otherwise it will run forever
clearInterval(interval);
}
i++;
$('.timeout').text(timeout);
$('.i').text(i);
}
var interval = setInterval(animate, timeout);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Timeout: <span class="timeout"></span>
<br /> I: <span class="i"></span>

Related

javascript, jquery. won't fadeOut

I am new to javascript and jquery, so, as a challenge, I am doing little game and ran into the problem today.
So, the code works like: there appears some text and after some time it needs to fadeOut, but it just won't fadeOut for me...
Here's my code:
var timeToStart = 3;
var timer = 0;
function count() {
document.getElementById("gameStarter").innerHTML = timeToStart + " s";
timeToStart = timeToStart - 1;
}
$("#start").click(function() {
$("#gameStart").fadeIn(500, function() {
timer = setInterval(count, 1000);
setTimeout(function() {clearInterval(timer);}, 4000);
if (timeToStart == 0) {
$("#gameStart").fadeOut(500)
}
});
});
(gcampbell and Patrick Evans pointed this out in the comments. As they haven't posted an answer, I'll post a CW.)
Your code here
timer = setInterval(count, 1000);
setTimeout(function() {clearInterval(timer);}, 4000);
if (timeToStart == 0) {
$("#gameStart").fadeOut(500)
}
only runs your if statement once, before everything is finished running. Right now it passes over it once, when timeToStart still equals 3. I recommend putting your if statement inside of your count() function like this
function count() {
document.getElementById("gameStarter").innerHTML = timeToStart + " s";
timeToStart = timeToStart - 1;
if (timeToStart == 0) {
$("#gameStart").fadeOut(500)
}
}
so it checks it every time its run, instead of only once.
Live Example:
$("#gameStart").hide();
var timeToStart = 3;
var timer = 0;
function count() {
document.getElementById("gameStarter").innerHTML = timeToStart + " s";
timeToStart = timeToStart - 1;
if (timeToStart == 0) {
$("#gameStart").fadeOut(500)
}
}
$("#start").click(function() {
$("#gameStart").fadeIn(500, function() {
timer = setInterval(count, 1000);
setTimeout(function() {
clearInterval(timer);
}, 4000);
});
});
<div id="gameStarter"></div>
<div id="gameStart">This is gamestart</div>
<input type="button" id="start" value="Start">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

How to make my script pause after reaching a certain condition for 1000ms

I've got a setInterval script that repeats logging "Hello world" 10 times.
I would like to make it stop for 1 second after repeating 10 times, then starting again and doing the process for ever.
here is what I have:
var i = 0;
var x = setInterval(function(){
console.log("Hello world");
i++;
if(i >= 10){
i = 0;
stopInterval()
}
},1000);
var stopInterval = function(){
clearInterval(x);
setTimeout(function(){
//restart the interval, but how do I do???
},1000);
};
However, it says stopInterval is not defined and I thought it was
So you need to use clearInterval and use the id that is returned from setInterval to clear it.
function myTimer() {
var i = 0,
interval = setInterval(function(){
console.log("Hello world");
i++;
if(i >=10){
clearInterval(interval);
window.setTimeout(myTimer, 1000);
}
},100);
}
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers
just with setTimeout and Recursion DEMO
var i = 1;
var delay = 500;
function callMe() {
console.log("Hello World"+i);
document.getElementById("pri").innerHTML = "Hello World " + i;
if (i == 11) {
i = 1;
delay = 1000;
console.log("......Restart");
document.getElementById("pri").innerHTML = "......Restart";
} else {
delay = 300;
}
setTimeout(callMe, delay);
++i;
}
window.onload = callMe;
<div id="pri"></div>

Run a jQuery .click event on an element every 5 seconds repetitively

I have an element which I want to be "clicked" every 5 seconds, does something, and then after 5 seconds it gets clicked again, does something, ect'.
So I used setTimeout, which does the job for the 5 seconds thing:
(found the example here: How to hide a div after some time period?)
And there's the jQuery event .trigger which I found here: JQuery automatic click after 4 sec
I tried looping it using 'for' and I got a .click event that happens after the first 5 seconds, and then uses the .click event again and again without the 5 seconds pause: http://jsfiddle.net/WTJgt/417/
In general, I built my first jQuery rotator :)!
with right and left buttons - and I want it to move a slide after x seconds by clicking it "without clicking".
This is my .click event code for the "next" element button:
// variables
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
$(".r-arrow").click(function(){
moveInPixles = ( rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
}
});
setInterval(function () {
$(".r-arrow").click();
}, 5000);
Edit:
Use setInterval and clearInterval so that you can reset the interval on button click. Your code needs refactoring because you can't really use it as it is.
var intervalId;
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
autoRotate();
function autoRotate() {
intervalId = window.setInterval(function () {
rotateStuff();
}, 5000);
}
function rotateStuff() {
moveInPixles = (rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
}
}
$('.r-arrow').on('click', function () {
window.clearInterval(intervalId);
rotateStuff();
autoRotate();
});
Dont do a click, but just trigger the javascript function every five seconds. by triggering a click you also activate all other functions listening to the event and some might be in conflict with your code or used by other libraries.
You can use setInterval() to do so.
Your code should looks like this :
// variables
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
var myFunction = function(){
moveInPixles = ( rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
}
});
$(".r-arrow").click(myFunction);
setInterval(myFunction, 5000);
It is important to assign setInterval to a variable then you will be able to stop it using clearInterval()
var intervalID = window.setInterval(code, delay);
Then when you need to stop it :
window.clearInterval(intervalID)
Would do the trick
var rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
In your click event add at
$(".r-arrow").click(function(){
window.clearInterval(rightArrowIntervalId);
// will destroy existing interval
moveInPixles = ( rotCounter + 1) * 746 * -1;
.....
// will create new interval in 5 seconds
rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
});
I don't fully understand the question, but if you want to call a function every 5 seconds rather than just once then use setInterval().
Use setInterval function instead of setimeout
$( function() {
$('#login').click(function() {
alert('login button clicked');
});
setInterval(function() {
$('#login').trigger('click');
}, 500);
});
check updated JSFIDDLE

Timer not running more than once

For some reason when I run the below script for the first time, the timer doesn't activate again for a second time, any idea why?
var timer = 0;
$(document).ready(function() {
$('#search').keypress(function() {
if(timer == 0) { $('#sel').html('<iframe src="search.php?p=' + $('#search').val() + '"></iframe>'); }
timer = 1;
setTimeout('timer = 0;', 2000);
});
});
Regards
Matthew
setTimeout only runs once. You probably want setInterval.
$('#search').keypress(function() {
if(timer == 0) { setTimeout('clearTimeout(this);timer = 0;', 2000); $('#sel').html('<iframe src="search.php?p=' + $('#search').val() + '"></iframe>'); }
timer = 1;
});
Running the timer inside it fixed it well :)

i want a delay of 100millisec while running each loop

for(i=100;i>=0;i--){
icon.style.filter="alpha(opacity=0)";
}
this is my for loop ... wat i want is tat each time for loop completes 1 loop it should wait or sleep for 100millisec so tat it can give a fadding effect....
You should call setTimeout, which will execute a function after a given delay.
For example:
function fadeOut(i) {
i = i || 100;
icon.style.filter = "alpha(opacity=" + i + ")";
icon.style.opacity = i / 100;
i--;
if (i > 0)
setTimeout(function() { fadeOut(i) }, 100); //Call fadeOut in 100 milliseconds
}
You can also call setInterval, which will keep calling the function until you call clearInterval.
For example:
function fadeOut() {
var i = 100;
var timer = setInterval(function() {
icon.style.filter = "alpha(opacity=" + i + ")";
icon.style.opacity = i / 100;
i--;
if (i <= 0)
clearInterval(timer);
}, 100);
}
You can do this much more easily using the jQuery library, like this:
$(icon).fadeOut();
John Resig wrote very cool JavaScript functions for fading in and out (Editing slightly):
function fadeOut(elem, time)
{
var t = time / 100;
var c = 0;
for (var b = 100; b >= 0; b -= 5)
{
c +=5;
(function(){
var pos = b;
setTimeout(function(){
setOpacity(elem, pos);
}, ((c + 1) * t));
})();
}
}
function fadeOut(elem, time)
{
show(elem);
var t = time / 100;
var c = 0;
for (var b = 100; b >= 0; b -= 5)
{
c +=5;
(function(){
var pos = b;
setTimeout(function(){
setOpacity(elem, pos);
}, ((c + 1) * t));
})();
}
}
function show(elem)
{
elem.style.display = '';
}
function setOpacity(elem, level)
{
if (elem.filters)
{
elem.style.filters = 'alpha(opacity=' + level + ')';
}
else
{
elem.style.opacity = level / 100;
}
}
You would then use it like:
var el = document.getElementById("#element");
fadeIn(el,1000); //Fade in over 1 second
fadeOut(el,1000); //Fade out over 1 second
EDIT:
Would be easier with jQuery, but you would learn how it works using normal JavaScript
$("#element").fadeOut();
$("#element").fadeIn();

Categories