On my upload file page I want to show an elapsed time (how long the user has been uploading the file for) in this format: 00:26, which would be 26 seconds. 17:34 would be 17 minutes 34 seconds, etc.
How could I do this? I have an event that gets called when the upload starts so I can set a Date variable from there, and I also have a function that gets called periodically for me to update the elapsed time.
Thanks.
Manually: Off the top of my head.
var s = 0;
var startTime = new Date();
var interval = setInterval(function(){
s++;
var temps = s%60;
var m = Math.floor(s/60);
document.querySelector("#timebox").innerHTML = ""+m+":"+ (temps>9?"":"0") + temps;
},1000);
Then when it is done uploading... it would need to call
clearInterval(interval);
However I would recommend using something like Moment.js though. Much more robust.
client side I'm guessing.
Sure, setInterval() a counter function that starts on the 'click' of the upload. Your counter function could return to screen a kind of 'progress' - is this what you mean ?
Related
I'm trying to decrement a variable once a day. I have written the following code for that.
var counter = 10; //any value
setInterval(function() {
counter = counter - 1;
}, 86400000);
Is there a better or efficient way to achieve the same thing ?
P.S : - I do not wish to use any libraries.
The only thing I see you miss is to set the initial value of counter variable.
I would write:
var counter = 1000; // or any useful value
setInterval(function() {
--counter;
}, 24 * 60 * 60 * 1000); // this is more self-explanatory than 86400000, and, being evaluated just once, it will have a tiny effect on the performace of the script
I don't see any problem in the way you write it. You use interval, ok, but this is not the worst evil you may do to set up the variable value.
You may think of another solution with a function which returns you the current counter.
var initialValue = 20000;
function getCounter() {
return initialValue - Math.floor(Date.now() / 1000 / 60 / 60 / 24);
}
console.log(getCounter());
The difference is that it takes the current day number starting from the UNIX time beginning. Every day the day number will be increased, so the result of the function will be decreased by 1.
But still I don't see how this solution can be better than yours.
I'm not totally sure why, but using setInterval like this makes me uncomfortable.
If I were to require this, I would use something like this approach:
var counter = 10;
var timeout = new Date();
setInterval(function(){
if(new Date() >= timeout)
{
--counter; // the action to perform
timeout = new Date(timeout.getTime() + 86400000); // update the timeout to the next time you want the action performed
}
console.log(counter);
},1000); // every second is probably way more frequent than necessary for this scenario but I think is a decent default in general
One thing that this allows is to, for example, set the next timeout to midnight of tomorrow rather than being locked in to "X seconds since the previous execution". The key is the inversion of control - the action itself can now dictate when it should next run.
Though I would probably abstract away the details behind an interface accepting a start, interval, and action.
The biggest problem in my eyes is that you have to keep this one JS process running consistently for days at a time to have it do what you need. The world is not so perfect that things don't need an occasional reboot...including the average JS process.
Personally I would store a timestamp of my starting point, then (whenever I need to know how much time has elapsed) grab a new timestamp and use it to calculate how many days it has been. That way even if something interrupts my process I can still be right where I started.
Maybe use window.localStorage to save the last time, and if it is greater than 60*60*24 (seconds in a day) set the last time to this morning/now/1:00 and then decrease the value and save it.
Example:
var d = new Date();
var mins = -(1+d.getHours())*60+d.getMinutes();
var secs = mins*60+d.getSeconds(); // total seconds passed today from 1:00
var now = d.getCurrentTime():
var lastCheck = localStorage.getItem("lastCheck");
if (!lastCheck)
{
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
var dayPassed = now - lastCheck > 24*60*60; // change to see if a day has passed
if (dayPassed)
{
// save seconds
localStorage.setItem("counter",localStorage.getItem("counter")-1);
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
It makes more sense to me to check how many days have passed since a specific date and decrement that number of days from the counter. Mostly just because I wouldn't expect anybody to leave the same page open without the need or want to reload for days on end. I would do something like this:
counter = 365; // original counter
var start = new Date(2016, 03, 20); // original date
var now = new Date();
var days = Math.floor(Math.abs(start.getTime()-now.getTime())/(24*60*60*1000))
counter -= days;
That way every time you visited the page, it would be decremented correctly. Note that this ignores any issues with leap days or time zones. The example above would have a counter of 360 for me. And then if you did expect it to be open for days, reload it automatically with:
self.setTimeout(function(){document.location.reload()}, 86400000);
I've created a sound installation for an exhibition. The sound file last for 24 hours. What I would like to do is to create a site just for this file. I want it to be as stark and simple as possible. A dark background and a white countdown that start once the file start's streaming and countdowns until the file ends. That's from hour 24 to 00:00.
All the countdown scripts count to an specific date and rarely restart themselves.
Is this even possible?
So if I get it right you want to know how to make a progress bar?
I'd say if you don't want to get too much into the niddy-griddy parts, I'd recommend bootsrap and jquery.
I made an example of something I would do:
http://jsfiddle.net/1tq6scga/3/
//JS
var song_seconds = 10;
c = 0;
i = 0;
var invt = setInterval(function(){
c = i/song_seconds;
c = (Math.round(c * 100 * 100)/100) + '%';
$('.progress-bar').html(c);
$('.progress-bar').css({'width':c});
i++;
if(i === song_seconds + 1) {
clearInterval(invt);
}
}, 1000);
so for you I would make it so that the variable max is the length of the song in seconds. Then I'd wrap this up in a function and do it so once a button play is clicked this code is ran in the background, and when I pause the song then the interval gets cleared.
I really don't wanna write more than this, because it requires coding a whole webpage. But this should be enough to get you started.
I'm trying to create something similar to a stop watch in an AngularJS app.
I've got a 'start' button that when clicked, the app will set a startTime variable which gets the current time and then I want another variable which updates every second and calculates the difference in seconds between the startTime variable and the current time which I can use as the stop watch value that's displayed to the user.
I'll also need to be able to stop and restart the timer so I'd like the stop watch value to be stored in seconds so that I can easily start the timer at any number of seconds and resume the timer.
What's the simplest way of doing this?
Expanding on my comments above, something like this...
var startTime = new Date();
$scope.stopwatch = 0;
$interval(function() {
$scope.stopwatch = (new Date() - startTime) / 1000;
}, 1000);
and in your template
<p>Seconds: {{ stopwatch }}</p>
Bonus points for creating a filter for formatting the seconds in hh:mm:ss format.
The best way to accomplish this, is by using $interval like so:
var stop, seconds=0;
stop = $interval(updatingFunc, 1000);
function updatingFunc(){
seconds++;
console.log(seconds);
if(seconds === 4){ // Here you set whatever condition to cancel the interval
$interval.stop(stop);
}
}
I have a home made(not by me of course) program that runs in milliseconds and I'd literally have to put millions of milliseconds to get it to do what I want it to do, so I'm trying to change it to seconds, or even minutes... I know the var milli is what I should be changing but dunno if I change it to var sec or var secs or var seconds or what, I'm not very knowledgeable of coding so I'm sure this is a simple answer, and I've tried a few different things that did not work, so that's why I came here, thanks if you can answer :) ignore the fact that it's not properly formatted as code in this post
<script>
var a=0;
var milli;
function collect1()
{
var milli = document.getElementById("numbers").value;
var links=document.getElementById('linkholder').value;
links = links.replace(/[\n\r]/gi , " ");
var link=links.split(" ",100000);
var iframe1=document.getElementById('iframe1');
iframe1.onload = function(){setTimeout(collect1, milli);};
iframe1.src=link[a];
a++;
Change this line
var milli = document.getElementById("numbers").value;
to
var milli = document.getElementById("numbers").value * 1000;
1 second is 1000 milliseconds.
Also note that this variable milli is not the same as the var milli; on the third line. If you want to turn that variable into seconds you need to multiply it with 1000 too.
1 sec = 1000 milliseconds
The only place you are using the milli variable in the code you've provided is here:
iframe1.onload = function(){setTimeout(collect1, milli);};
so if you want the whatever the milli variable is to actually be how many seconds you want to wait then multiply it by 1000:
iframe1.onload = function(){setTimeout(collect1, milli*1000);};
Side note: That is going to wait a long time....
It is hard to guess, what your code is meant for, since I don't know what your html page looks like.
But since the variable milli is only used once (as a parameter to setTimeout), I would guess that you could change that line of code from:
iframe1.onload = function(){setTimeout(collect1, milli);};
to:
iframe1.onload = function(){setTimeout(collect1, milli * 1000);};
and see what is happening.
Let me explain what I'm trying to do.
I want to make a simple box which counts down numbers at intervals I specify.
For example, I'd like to set it to start at 150, and then I want to set it to drop by 15 every 30 seconds.
Is this possible with AJAX/Javascript? If so, could someone point me in the right direction?
Would really appreciate any help on this script, been Googling for hours now! :(
Cheers
Kieran
Have a look at the setTimeout or setInterval methods, they allow you to execute a function after a specified number of milliseconds (1000ms = 1second). Use that, to call a function that keeps dropping the number and writes it to a HTML element to the user can see it.
this isn't tested, but i hope it shows you the way to go.
var start = 150;
var drop = 15;
var interval = 30;
function countdown(){
document.getElementById('mybox').innerHTML = start;
start-=drop;
window.setTimeout("countdown",interval*1000);
}
countdown();
You may use jQuery to do that, see http://keith-wood.name/countdown.html -> tab Callbacks
Keep in mind that 30 seconds in my browser are not necessarily equal to 30 seconds in your browser. It depends on the workload of the browser.
The time difference is minor for a short time but can increase over a long time. The times will drift apart. If the times must not be equal (or nearly equal) between two visitors than such simple solution should be fine.
We had once a problem to introduce a live clock / countdown in one of our projects. We build a script with javascript, ajax and PHP for clock synchronisation (server time was timeserver).
You should use setInterval / clearInterval which is made for this kind of tasks:
function cooldown(element, start, stop, step, delay) {
var current = start;
element.innerHTML = current;
var timer = setInterval(function () {
current -= step;
if(current < stop) current=stop;
element.innerHTML = current;
if(current == stop) clearInterval(timer);
}, delay*1000);
}
Demonstrated here : http://jsfiddle.net/PCMHn/