Countdown from 60 to 0 in javascript and loop - javascript

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

Related

How to create a simple countdown timer in JS?

I have very little experience in coding in general, however, I still need a timer that comes on a pop-up that goes from 20 or 30 minutes to 0, and it should display the time remaining (like MM:SS). Then, when the timer hits 0, a new pop-up should appear that displays some plain text. Is this even possible?
This could do the work
let time = 5;
let element = document.getElementById('countdown');
function lower() {
if(time >= 0) {
element.innerHTML = time--;
}
else {
console.log('popup')
//open popup here
}
}
setInterval(lower, 1000);
I did not do the time format tho. Only shows in seconds now

jQuery fadeout time confusing with different results

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

Rails timer countdown, which doesn't reset after page refreshing

I'm creating Rails web application. I want create timer for 15 seconds, which does not reset when I refresh page. I've tried use jQuery countdown from Keith Wood but when I refresh page, timer resets. So, I think I need create timer on backend but I can't imagine how realize this. Can anyone help? There is my timer code below
$('#timer_' + auct_id).countdown({until: +15, onTick: function(periods) {
var seconds_addition;
if (periods[6] < 10)
seconds_addition = '0';
else
seconds_addition = '';
$('#timer_' + auct_id).text('0' + periods[5] + ':' +
seconds_addition + periods[6]);
}});

Track total time taken for a task

I am building a site where task is assigned to each user and he/she needs to complete the task within a fixed duration of time.
For this is need to track Time taken on each task. I also need to track if the user is sitting idle on the site.
Right now i can do this using this code :
HTML
<a class="btn btn-success btn-lg" id="startTracking" role="button">Start Tracking</a>
<a class="btn btn-danger btn-lg" id="endTracking" role="button">Stop Tracking</a>
<h2 id="testingSince"></h2>
JAVASCRIPT
<script type="text/JavaScript">
var totalSeconds = 0;
var idleSeconds = 0;
$(document).ready(function () {
$('body').on('click','#startTracking',function(){
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
});
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleSeconds = 0;
});
$(this).keypress(function (e) {
idleSeconds = 0;
});
});
function timerIncrement() {
totalSeconds += 1;
idleSeconds += 1 ;
if (idleSeconds > 600) { // 20 minutes
alert('You have been sitting Idle for 10 Minutes');
}
$('#testingSince').text(timeStringfromSeconds(totalSeconds));
}
function timeStringfromSeconds(totalSeconds){
var hours = Math.floor(totalSeconds / 36e2),
mins = Math.floor((totalSeconds % 36e2) / 60),
secs = Math.floor((totalSeconds % 60));
return ("0" + hours).slice(-2)+':'+("0" + mins).slice(-2)+':'+("0" + secs).slice(-2);
}
</script>
So this code works great and the user can see the time spent since he clicked the button. It also tracks user idle time and gives an alert after 10 minutes.
However the only Problem here is that when the page reloads the counter starts from 0. i.e the 2 lines :
var totalSeconds = 0;
var idleSeconds = 0;
I just want the timer counter not to restart and continue from its previous value.
One way of doing this is using Cookies. So i have to update them every second but i am not sure if this is a good Idea.
Please let me know if there is any other way or i need to use browser cookies ?
Many users will not permit cookies on their computers. You should never rely only on cookies. Maybe you should make some script that you can ajax call every second or two or five and store elapsed time in session.

Javascript: Controlling an image's moving speed

I'm a beginner and currently I can move an image from left to right and I can turn it back to its initial point when moving finishes. What I want to do is also controlling image's speed. In order to do this I tried the codes below:
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(speed) {
var pp = document.getElementById("myimage");
var lft = parseInt(pp.style.left);
var tim = setTimeout("moveRight()", speed);
lft = lft + 50;
pp.style.left = lft + "px"
if (lft > (userWidth) + 80) {
document.getElementById("myimage").style.left = 100 + "px";
clearTimeout(tim);
}
}
</script>
And html:
<form>
<input type="button" value="Speed 1" onclick="moveRight(50)" />
<input type="button" value="Speed 2" onclick="moveRight(25)" />
<input type="button" value="Speed 3" onclick="moveRight(10)" />
</form>
My problem: there is no difference when I click any of three buttons. Image is always moving with the same speed and looks like buttons have no control on the speed.
The mistake you did in your orignal code is that when you call the function again you do not pass it the value of speed which means that the only thing that happens is that the first animation is delayed.
Try replacing the call with this line and then your code should work.
var tim = setTimeout("moveRight("+speed+")", speed);
With this you can still do this without using Jquery
Your above code doesn't have any speed logic. The only thing you're doing is delaying the time before the animation start :
var tim = setTimeout("moveRight()", speed);
Making a recursive call to a function waiting for an attribute (speed), is also a nogo.
I setted up a quick fiddle to demonstrate jquery animation speed :
http://jsfiddle.net/yeQtB/
To achieve speed in animation, two possibilities :
• Cycle logic :
You admit that rather than seconds, you can work with cycles, then just create a for loop, that will iterate until animation is over. edit : this is just here for the sake of the explanation
• Time logic
You have a distance and a timeframe (in sec), divide the distance by the timeframe, it gives you step, divide the distance by the step, it will give you the number of steps, then it is just a matter of creating a settimeout firing every second in a loop. edit : if you achieved this and is eager to go for something a bit smoother, i'd advise to have a look at the requestAnimationFrame HTML5 Api :
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
You have to pass the variable speed to moveRight in the setTimeout :
var userWidth = window.screen.width,
tim,
pp = document.getElementById("myimage"); // You should cache your variables
function moveRight(speed) {
var lft = parseInt(pp.style.left) || 0;
tim = setTimeout("moveRight(" + speed + ")"); // Here you have to pass speed as a parameter
lft = lft + speed; // Here I guess it is speed rather than 50
pp.style.left = lft + "px"
if (lft > (userWidth) + 80) {
pp.style.left = 100 + "px";
clearTimeout(tim);
}
}

Categories

Resources