progress-bar updated with setInterval zero still takes time to finish - javascript

Sorry for being very noob, but I started to learn JavaScript and have a little problem.
In the following code sample, the progress bar goes from 0 to 100 in 1 second, however, the "time" variable is set to 0 milliseconds, used by setInterval. I would expect the progressbar to be instantly at 100% when I press the button. (I will have progresses that will take less than a second to finish and I want to show them properly.) Looks like the setInterval is not using the given time as milliseconds.
So my question is, how can I set up the setInterval to use milliseconds, as it should be? (I know it will behave strange if you click the button a second time, but now this does not matter.)
Thanks!
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<button id="theButton">click</button>
<progress id="progressbar" min="0" value="0" max="100"></progress>
<span class="progress-value">0%</span>
<script>
$('#theButton').click(function(){
var progressbar = $('#progressbar'),
max = progressbar.attr('max'),
time = 0,
value = progressbar.val();
var loading = function() {
value += 1;
addValue = progressbar.val(value);
$('.progress-value').html(value + '%');
if (value == max) {
clearInterval(animate);
}
};
var animate = setInterval(function() {
loading();
}, time);
});
</script>

Related

How call this function 10 times

I was working on something where a duck disappears every time he is clicked and re appears 1 second later. But i want to make him reappear only 10 times and then stop after that. So what is a simple approach to make it appear only 10 times? I have tried using loops, but i was not able to do it properly.
You could use a counter like below. You just have to edit my code a bit to suit your purposes.
var counter = 0;
$(".button").click(function() {
if (counter < 10) {
$(".text").hide();
counter++;
setTimeout(function() {
$(".text").show();
}, 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button">Click</button>
<p class="text">Text</p>

Simple javascript counter that can be paused and resumed after web page has been closed

I need to create a very simple Javascript-based counter, which counts currency (so two decimal places) and increases in value by 0.18 every minute. The idea is to represent "live" estimated savings by the company's new solar panels, and this counter will be started and stopped by an employee every day, to continue the next day.
I found a fiddle by somebody else for a start/resume counter: http://jsfiddle.net/f9X6J/
HTML:
<span id="hour"></span>
<span id="min"></span>
<span id="sec"></span>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
Javascript:
var Clock = {
totalSeconds: 1000,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(Math.floor(self.totalSeconds / 3600));
$("#min").text(Math.floor(self.totalSeconds / 60 % 60));
$("#sec").text(parseInt(self.totalSeconds % 60));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
};
Clock.start();
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
This is great so far, but I please need the following:
It must not calculate time, but rather money.
It must be saved to the server in case the computer shuts off.
Thanks!
For the sake of beginners in 2019. The answer to the two questions are,
1) Keep a counter outside the clock object and keep adding 1 to it every second the clock is active. This will give the total number of seconds the clock has been active. This can be then converted to total savings at any point.
2) Don't jump on to server side stuff just yet. Try to store the total with localStorage which persists even if the computer is switched off until browsing data is cleared in the browser. This will avoid lot of added complexity. An example for storing values locally and reading from them is below.
<html>
<head></head>
<body>
<div id="counter"></div>
</body>
<script>
var counter;
if( localStorage.getItem("counter") == null) {
counter = 0;
localStorage.setItem("counter", counter);
} else {
counter = localStorage.getItem("counter");
}
document.getElementById('counter').textContent = counter;
setInterval(function(){
counter = parseInt(counter)+1;
localStorage.setItem("counter", counter);
document.getElementById('counter').textContent = counter;
},1000);
</script>
</html>
Hope this provides a right direction.

How do I make an interactive backwards progress bar that works with a timer?

Is there any way that I could be able to make a progress bar go backwards? I have seen an example that told me to turn the progress bar 180 degrees, but that seems like a very dirty way to do it. What I'm looking for is so the progress bar can be time controlled, and so that a by pressing a button, I would add three seconds to the timer, thus pulling back the bar a bit (Say the timer is at 7 seconds, pressing the button would add a second, bringing it to 8 seconds thus pulling back the timer a little bit). If I could incorporate this with a countdown timer as well, it would be cool, but not 100% needed. Here is what I have so far. Changes that need to be made is so that the timer goes backwards instead of forwards, and so I could be able to add time on to it by pressing a button.
HTML:
Javascript:
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
}
setTimeout(animator, updatesPerSecond);
});
JSFiddle
1st: - We will create a new function for reverse
2nd: - Add min="0" attribute to the progress bar
3rd: - change progress value to 200 progress.val('200'); before running the setTimeout()
Finally: - change + to - on progress.val() - interval
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
},
reverse = function(){
progress.val(progress.val() - interval);
$('#val').text(progress.val());
if ( progress.val() - interval > progress.attr('min')){
setTimeout(reverse, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('min'));
}
}
progress.val('200');
setTimeout(reverse, updatesPerSecond);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress max="200" min="0" value="1"></progress>
<div id="val"></div>
Simply start with progress.val at its maximum, and decrement it. When it gets to 0, you're done.

Adding Time Buttons in JQuery Timer

I am trying to adapt the countdown timer from http://www.jqueryscript.net/time-clock/Simple-jQuery-Html5-Based-360-Degree-Countdown-Timer-countdown360.html to add buttons which determine the time to count down.
I am a little confused (no, really a lot confused) about
a) how to link the buttons to the countdown display,
b) how to stop the display starting until I have clicked the desired button, and
c) how to reset the process without reloading the page.
Currently it takes the initial seconds value of 10 (put there just to test to see what it is doing) but does not respond to the buttons.
Here is the html:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="../src/jquery.countdown360.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="container">
<div id="countdown"></div>
<script type="text/javascript" charset="utf-8">
$("#countdown").countdown360({
radius : 50,
seconds : 10,
fontColor : '#FFFFFF',
autostart : false,
onComplete : function () {//will ring bell
}
}).start()
</script>
<script>
window.onload = init;
function init(){
document.getElementById('btnStart1').onclick = start1;
document.getElementById('btnStart2').onclick = start2;
document.getElementById('btnReset').onclick = cdreset;
start.countdown360();
}
function start1(){ // starts 1 min countdown
seconds = 60;
countdown360();
}
function start2(){ // starts 2 min countdown
seconds = 120;
countdown360();
}
function reset() { // resets countdown
seconds=0;
//???
}
</script>
</div>
<div id="container">
<div id="countdown"></div>
<input type="button" value="1 min" id="btnStart1"/>
<input type="button" value="2 min" id="btnStart2"/>
<br>
<input type="button" value="Reset" id="btnReset"/>
</body>
</html>
Any help would be most welcome!
Answer & Demo
So it turns out there isn't a legit way of doing this, truth be told there isn't a lot of documentation about the subject and the plugin itself doesn't provide such functionability, or at least not in a user friendly way.
But I went down to the guts of the code and managed to make it work.
Here is a JSFiddle where I demonstrate what I understood you wanted.
HTML
<div id="countdown"></div>
<button id="start">Start</button>
<button id="set60">Set 60s</button>
<button id="set120">Set 120s</button>
<button id="reset">Reset</button>
JavaScript
start = document.querySelector("#start");
set60 = document.querySelector("#set60");
set120 = document.querySelector("#set120");
reset = document.querySelector("#reset");
div = $("#countdown");
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
pingSound.preload = "auto"; //<- Optional but recommended
countdown = div.countdown360({
radius: 50,
seconds: 30,
fontColor: '#FFFFFF',
autostart: false,
onComplete: function () {
pingSound.play();
}
});
countdown.start(); //This right here is for showing the clock on load.
countdown.stop();
start.onclick = function () {
startCountdown(countdown);
}
set60.onclick = function () {
setSeconds(countdown, 60);
}
set120.onclick = function () {
setSeconds(countdown, 120);
}
reset.onclick = function () {
setSeconds(countdown, 0);
}
function startCountdown(countdown) {
countdown.start();
}
function setSeconds(countdown, seconds) {
countdown.stop();
countdown.settings.seconds = seconds;
countdown.start();
}
Explanation
Variables
start, set60, set120, reset : Link to their respective button elements.
div : Link to the countdown div element.
pingSound : Audio element that contains the "ping" sound.
countdown : The countdown object itself, you need to declare it like this, passing the initial properties and saving it in a variable.
Functions
startCountdown(countdown) : Takes any countdown object and start's it's execution, this will get the countdown running.
setSeconds(countdown,seconds) : Takes any countdown object and set's it second (it can be used in mid-excecution). It works by first stopping the countdown, then updating the Countdown.settings.seconds property, which is the actual seconds the countdown will run.
Development
With those variables & methods, how I did it is pretty straight forward.
If you want the clock hidden until you play it:
We first create the countdown object and hide the div.
div = $("#countdown");
div.css( "display" , "none" );
countdown = div.countdown360({..});
Why? Well because of how the plugin works. As soon as you create the countdown your div is made bigger by the plugin, and you need to create the countdown there because that's the only way it works, so if you don't want a blank square of nothing (since we haven't started the countdown) you have to hide the div itself.
So, we add an onclick event to each button:
for start -> startCountdown(countdown) , div.css( "display" , "block" ); -> Starts the countdown and shows the div.
for set60 -> setSeconds(countdown,60) -> Sets the countdown to 60s.
for set120 -> setSeconds(countdown,120) -> Sets the countdown to 120s.
for set0 -> setSeconds(countdown,0) -> Sets the countdown to 0s.
And that's it, it took me a while to figure out, hopefully I didn't just bore you to death, and may I suggest getting a better plugin next time? Good luck :)
If you want the clock displayed on load:
Okey, so this is an update upon your request, if we part from my original code, to make the div appear on load is quite simple (JSFiddle & code here have been updated)
We first create the countdown object, then start it and inmeadiatly stop it (freezing it until you start it again).
countdown = div.countdown360({..});
countdown.start();
countdown.stop();
Now, we add the same onclick events to the buttons except for the start button, which will no longer have to display the div as block as it isn't hidden.
for start -> startCountdown(countdown) -> Starts the countdown.
(..)
If you want to play a sound at the end of the countdown:
For the ping sound to play in the end, you just need to create a new Audio object with the mp3/ogg src as a parameter:
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
Then, preload the audio so it's ready to play (otherwise when you call play it will first have to load). This is optional but recommended.
pingSound.preload = "auto";
And then call the Audio.play() function in the countdown's onComplete event.
countdown = div.countdown360({
(..)
onComplete:function(){
pingSound.play();
}
});
That's it, happy coding :)
Updates
Updated code to display the clock on load (1:43p.m 31/12/14)
Updated code to play sound in the end of countdown(6:10p.m 02/01/14)
First you don't have jquery.js and you are using $('#countdown')
You don't have any function called cdreset .
Well I wrote a similar code for you :
<script>
var m = setInterval(start, 1000), // init the interval , every 1 sec will call start function
s = 60;
function start(){
s = s -1;
document.getElementById("count").innerHTML = s;
}
function stop(){
clearInterval(m);
}
</script>
<p id="count">60</p>
<input type="submit" onclick="stop()" value="stop" />
it will count down starting from 60 to -XXX
You should add a condition so as to stop the timer at 0 :)

How can i add a div based on TIME using js or jquery?

I want to create a timer that will add or remove divs ( inline divs ) based on time function in Javascript or Jquery.
E.g With each second i want to add a div or remove a div.
Can i get some ideas on this?
<html>
<head>
<title>Testing</title>
<script>
var i = 0;
var myVar=setInterval(function () {myTimer()}, 1000);
function myTimer()
{
document.getElementById('Container').innerHTML += "<div id='"+i+"'>This is the Div with New ID 'i'</div>";
i++;
}
</script>
</head>
<body>
<div id='Container'>
</div>
</body>
</html>
This Should Create a DIV each second inside the Div with id 'Container'
Use setInterval.
var diff = 1000, // how long between adds in milliseconds
totalTime = 0, // how long we have run
maxTime = 1000*60*60*5, // how long we want to run
interval = setInterval(function() {
$(".parentDiv").append($("<div>new div</div>"));
totalTime += diff; // keep track of all of our time
if (totalTime >= maxTime) {
clearInterval(interval);
}
},diff);
Note that the time is in milliseconds.
And to get rid of it
clearInterval(interval);
Beware that it will keep running, and if any of your actions take too long or slow down, you could find yourself with quite the mess stumbling over each other.
You can make use of setTimeout(function, mili seconds)
var testTimer;
function timer()
{
// Do your stuff
testTimer = setTimeout("timer()",1000);
}
This will call your timer function every one second. and you can do your stuff in this function
To stop this timer function you can do
window.clearTimeout(testTimer);

Categories