jQuery fadeout time confusing with different results - javascript

Below is the code i was asked in interview.
What would be the difference between Start & End time in this case?
I found running it here takes 12 seconds, while in this link it takes 8 Seconds..!
And above all the confusion is, in each loop the console prints the fadeout animation time increasing by 2 seconds, though it completes in total 2 seconds for each div.
Can anyone explain in details what's happening here exactly?
function getMinsSecs() {
var dt = new Date();
return dt.getMinutes() + ":" + dt.getSeconds();
}
$("input").on("click", function() {
$("p").append("Start time: " + getMinsSecs() + "<br />");
$("div").each(function(i) {
console.log(1000 * (i * 2));
$(this).fadeOut(1000 * (i * 2));
});
$("div").promise().done(function() {
$("p").append("End time: " + getMinsSecs() + "<br />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<input type="text" id="inp">

I'll try to explain it within your code:
// if there are 5 <div> elements on the page, what will be the difference between the start and end times displayed?
/**
* This function gets the current date and prints
* the minutes and seconds in the following format
* mm:ss
*/
function getMinsSecs() {
var dt = new Date();
return dt.getMinutes() + ":" + dt.getSeconds();
}
/**
* Here we are adding a click event listener to the
* input present in the HTML.
*/
$("input").on("click", function() {
// This line appends to the p present in the HTML
// the text with the current minutes and seconds (start time)
// and the a break line.
$("p").append("Start time: " + getMinsSecs() + "<br />");
// This line goes through each div present in the HTML fading out each div multiplying it by the i (index).
$("div").each(function(i) {
console.log(i);
console.log(1000 * (i * 2));
//The fadeout function lasts the amount of milliseconds passed as an argument
$(this).fadeOut(1000 * (i * 2));
});
// This line waits til every function called over
// the divs end (this is what the promise function does).
$("div").promise().done(function() {
// This function is called after all the
// fadeout calls got executed and prints again
// the minutes and seconds appending the current minutes
// and seconds (end time)
$("p").append("End time: " + getMinsSecs() + "<br />");
});
});
Based on the comments, the first items gets fade out immediately because i = 0, then you have four (4) divs left and 4 * 2 = 8 so the difference between start and end time would be eight (8) seconds.
I hope it helps!

in a fiddle here, you get two bonus div's for the "console" output (one inside the other ... so that explains the 2 x 2 second extra time
in each loop the console prints the fadeout animation time increasing by 2 seconds, though it completes in total 2 seconds for each div.
No, first div takes 0 seconds to fade
Second div takes 2 seconds to fade completely
Third div takes 4 seconds to fade completely
Fourth div takes 6 seconds to fade completely
Fifth div takes 8 seconds to fade completely
Look closely and you'll see that they all start fading concurrently, at different rates

8 is the right answer. The promise will be done after 8s because the longest duration of fading is 4*2(s) for the last div.
The code snippet run on this site is having a bug. It include 2 more divs that don't belong to your code. Try to replace
console.log(1000 * (i * 2));
to this
console.log($(this));
and you will able to know what is going wrong

Related

3 Timeout intervals to show div jquery

<div class="popup_div">Form here</div>
What I am doing is to make this "div" popup when the page loads after 5 seconds, then when the user closes the popup div it will count again to 15 seconds to appear again, then when the user closes it again it will show for another 30 seconds
This is the interval
5 secs (on page load)
15 secs
30 secs (final popup, it won't popup after this)
Here is My fiddle, hope this helps
https://jsfiddle.net/3xk725ts/
Here I wrote a solution using setTimeout instead of setInterval so you don't need to take care about clearing it.
var iteration = 0;
var times = [5000, 15000, 30000]
var showPopUp = function(time) {
setTimeout(function() {
$('#timer').show();
$('#timer').html("<span class='close'>X</span><h3>Count down complete</h3>"); }, time)
}
showPopUp(times[iteration]);
$('body').on('click', '.close', function() {
$('#timer').hide();
iteration +=1;
if (iteration < 3) {
showPopUp(times[iteration])
}
});

Countdown from 60 to 0 in javascript and loop

As some of you guys may know, I am still developing my game LOL.
Right now I have basic functionality. Players can see their profits display and buy stuff if they have enough money.
All i need now is to display how quick players are getting money. So players are supposed to have money generated every 60 seconds. The money gets generated but it has no visuals.
What i want is for people to see how much to they have left before they get the next money.
so i have all the styling and that done for the timer. What i want is some vanilla javascript code to display the innerHTML for the time decrementing from 60 down to 0;
I have tried intervals with if statements and switch cases and ive tried a for loop but i cant get it to reset or even do anything.
Below is some of my code.
Code:
// Income Ticker Display (displaying time until next pay day)
var incomeTicker = 60;
window.setInterval(function(){
if (incomeTicker > 0)
incomeTicker--;
document.getElementById("incomeTicker").innerHTML = "Next Profit In : " + incomeTicker + " seconds";
}, 1000);
<span class = "incomeTicker" id = "incomeTicker" > Next Profit In : 60 seconds </span>
i have tried different ways of doing this and have looked a few questions but nothing is giving me what i need.
Thanks for any advise in advance.
ps. let me know if you need more code examples.
OKAY I FIXED MY LOOPING ISSUE AS WELL
// Income Ticker Display (displaying time until next pay day)
var incomeTicker = 60;
window.setInterval(function(){
if (incomeTicker > 0)
incomeTicker--;
document.getElementById("incomeTicker").innerHTML = "Next Profit In : " + incomeTicker + " seconds";
if (incomeTicker <= 0)
incomeTicker = 60;
}, 1000);
<span class = "incomeTicker" id = "incomeTicker" > Next Profit In : 60 seconds </span>
Thank you every one for helping me solve this problem

Body Background based on hour of the day JS

<script type="javascript">
jQuery(document).ready(function($){
var dt = new Date();
var currentHour = dt.getHours();
$('body').css('background', '#FFF url(https://crystalforums.cf/bk/bk_'+currentHour+'.png) no-repeat center center fixed');
$('body').css('background-size', 'cover');
});
</script>
Hey! I had this script working on a my forum and i tried working it on a my website index, but it seems to not work. They both use the body thingy (I forgot the actual term, it's Saturday and i got a ton of work) so they should effect the body element right? What am i doing wrong, the script suppose to set the background image of the website to a new image based on every hour. Help???
I don't want it to auto update, they cxan refresh. I want so there is one background for every hour.
First...I don't recommend use javascript for this....Your approach needs an user for an hour into your website and in the same page...If you still think in change that you will need use setTimeout function...
My recommendation is using a server side technology for this...
You can use setInterval() with duration set to 5 minutes 60000 * 5 or briefer duration between function calls
$().ready(function() {
var interval, curr;
function handleBackground() {
var dt = new Date();
var currentHour = dt.getHours();
if (!curr || currentHour !== curr) {
curr = currentHour;
$('body').css('background', 'url(https://crystalforums.cf/bk/bk_'
+ currentHour
+ '.png) no-repeat center center fixed');
}
}
// call `handleBackground` to set initial `background` at `body`
handleBackground();
interval = setInterval(handleBackground, 60000 * 5);
});
plnkr http://plnkr.co/edit/5YTPgPgaKbXfYIT0MG3x?p=preview
I don't know JQuery, I always use Java Script :P,
If you want to change background after 5 Minutes you can do this by javascript
<script>
index = 0;
function changeBackground(){
var backColor = ["image.jpg","image2.jpg","image3.jpg","image4.jpg"];
document.body.style.backgroundImage = "url("+backColor[index]+")";
index++;
if(index > (backColor.length) - 1){
index = 0;
}
}
//1000 means 1 second, so for 5 min
// 6,000 X 5 = 30,000
setInterval(changeBackground, 30000);
</script>
Just try this code.
You can use the setInterval() function like this:
function someFunction() {
alert("It's been one hour");
}
setInterval(someFunction, 3600000);
Where the 3600000 is a hour in milliseconds.

Progress bar with .delay

Fiddle
I want to make a progress bar fill up 25% per second. My current code makes it go to 100% and stay there on click. I'm not sure if it's best to use jquery or css. Or if there is an easier way to do it.
Also how can I make an action occur multiple times from one .click. Like you click battle and it hits the monster, then waits for the progress bar to fill, then hits the monster again and so on?
$('#battle').click(function() {
$('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage");
$('#bar').val(25).delay(1000);
$('#bar').val(50).delay(1000);
$('#bar').val(75).delay(1000);
$('#bar').val(100);
});
Here you go!
https://jsfiddle.net/6nrjw0Le/
For your example I am using
setTimeout()
Your example edited.
var progress = function(sec){
var interval = 250;//milliseconds
setTimeout(function(){
sec = sec+25;
$('#bar').val(sec);
if(sec < 100)
progress(sec);//call self with new value
},interval)
}
$('#battle').click(function() {
$('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage");
/*$('#bar').val(25).delay(1000);
$('#bar').val(50).delay(1000);
$('#bar').val(75).delay(1000);
$('#bar').val(100);*/
progress(0);//initialize progress bar
});
delay() is asynchronous. Putting one delay after another doesn't mean you get the execution after first one is complete.

Transition positioning

I have some code that I would like to integrate into the a website and have it be in the middle of the screen. This code does some fading with Javascript. But I can't move it around the screen like I would like to. When I move it around it messes up the animation.
Here is the HTML
<!DOCTYPE html>
jQuery fade-ins with a JavaScript for() loop
<div id="elem0" class="toBeFaded">Here's the first message...</div>
<div id="elem1" class="toBeFaded">We have second one here...</div>
<div id="elem2" class="toBeFaded">And here's the third message...</div>
<div id="elem3" class="toBeFaded">OMG!!! Here's the fourth message!</div>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/fadeCode.js" defer="defer"></script>
​
Javascript
$(function (){
var yourFade = 1, // the amount of time in seconds that the elements will fade in AND fade out
yourDelay = 2, // the amount of time in seconds that there will be a delay between the fade ins and fade outs
fadeTime = yourFade * 1000, //convert fade seconds to milliseconds (1000)
delayTime = yourDelay * 1000, // convert delay seconds to milliseconds (2000)
totalTime = fadeTime + delayTime, //3000 milliseconds...needed for all those delays we talked about
allElems, // find out exactly how many page elements have the 'toBeFaded' class (4)
elemNoFade, // Will help us find the last element represent the last element (3)
i,
fadingElem;
for (i = 0, allElems = $('.toBeFaded').length, elemNoFade = allElems - 1; i < allElems; i+=1) {
fadingElem = "#elem" + i;
if (i === 0) {
$(fadingElem).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
} else if (i === elemNoFade) {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime);
} else {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
}
} });​
and CSS
.toBeFaded {
display: none;
position:absolute;
font-size:70pt;
}​
and a link to jsfiddle
I'm not sure I see the problem. Take a look at this fiddle: http://jsfiddle.net/joplomacedo/6xfKN/375/

Categories

Resources