MomentJS on Angular to keep changing value on realtime [duplicate] - javascript

This question already has answers here:
Angular 6 run a function in every X seconds
(5 answers)
Closed 2 years ago.
I have an array of objects that has a property called startedTimestamp. I need to show on the front-end how long ago that has been running, on this case I'm using MomentJS with the fromNow() method. However, that will not updating as the time goes by... to something like 1 minutes ago... and then 2 minutes ago... and so on. Is there a way around that?
I'm using Angular.
Thanks

I cannot recreate an angular scenario here but it seems setInterval will do the trick. It's important to create the moment object just once (outside setInterval) then the label's text will be updated every second.
Run the code and wait at least a minute and you'll see how it changes from 'a few seconds ago' to 'a minute ago'
const label = document.querySelector('label'),
span = document.querySelector('span');
const m = moment();
let secondsPast = 0;
setInterval(()=>{
span.textContent = `${++secondsPast} seconds past`
label.textContent = `${m.fromNow()} from ${m.format()}`
},1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<span></span><br><br>
<label></label>

Related

JS How to count seconds to make bot do an operation every second

I am trying to make a cookie clicker game, and one item that you can get in shop is a bot where it adds x amount of credits to your current amount of credits every second. I want to be able to make multiple of these bots with variations, so not sure if setInterval would be usable in this case. How can I make this?
Note: The timer only starts when a variable is turned to false, so the timer shouldn't start when the app is opened.
P.S. I am using React
let bought = false
const [credits, setCredits] = useState
if (bought) {
For every second {
setCredits(credits+1)
}
}
I think you have to calculate seconds after each reaction on click,
you should use setInterval() in JavaScript function.
Example --
let time = document.getElementById("time");
function clock(){
let date = new Date();
let clocktime = (date.toString().split('G')[0]);
time.innerHTML = `${clocktime}`;
}
setInterval(clock, 1000);
First target an element then change its text to this function's output, and give time here in setInterval() function, for how many seconds you want to repeat that function (for how many seconds)

How do I send alerts every minute? [duplicate]

This question already has answers here:
JavaScript: get code to run every minute
(3 answers)
Closed 5 years ago.
I'm new to html and javascript but I was wondering how I could go about sending alerts like this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_alert every minute or so.
setInterval(() => {
// your code
}, 1000)
https://www.w3schools.com/jsref/met_win_setinterval.asp
javascript have a method to repeat something like a task every so often, this method is the function setInterval this function repeat that you want.
Javascript:
setInterval(function(){
alert("Hello");
}, 3000);
For example this method shown every 3 seconds an alert that say "Hello", if you want repeat a task every 3 minutures you need change 3000 to 180000 like this:
setInterval(function(){
alert("Hello");
}, 180000); // repeat every 3 minutes
Here is the docs of the function.
I hope it helps you, regards!

setInterval time not precise [duplicate]

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 5 years ago.
I'm developping an ionic app.
I create a counter with setInterval.
let test = new Date().getTime();
setInterval(() => {
console.log(new Date().getTime() - test);
test = new Date().getTime();
}, 1000);
Problem, the console.log give not the answer 1000. It is completely random and sometimes more thant 3000.
Have you an idea why is it so?
There is no way to guarantee the exact time because even the simplest function like this it takes some millisecond to execute the content inside the interval function. setInterval function only guarantee the time interval.

A counter made in Node.js which changes its value at definite time intervals

I am asking help for a problem which I am not able to solve despite every effort. I am trying to make a counter. This counter is to be placed in a div under the available items on a webpage. This counter should be able to change its value at predefined values and intervals, for example, the value starts at 5,000 at then decreases by 1 after 2 seconds and then by 4 after next 5 seconds and then by 3 after next 2 seconds and then the process repeats (decreases by 1 after 2 seconds...) three or four sets of variation will be enough.
The value shown by the counter must not be affected by the number of page loads or simultaneous users, also it should remain if the user sees the page in two different browsers, it must only be shown as described above.
This counter must be capable of changing its value without needing the user to refresh the page.
Most straightforward solution as it appears to me would be to make the timer relative to absolute time.
This means you take the time passed since an arbitrary point in time you define as the start, e.g. right now which is var start = Date("Thu Jun 04 2015 01:46:44 GMT+0200 (CEST)") here. You can now subtract start from the current time to learn how much time has passed:
var passedSeconds = (new Date() - start) / 1000;
We divide by 1000 since JS calculates with miliseconds by default.
To update the timer, do a simple
setInterval(function() {
var passedSeconds = (new Date() - start) / 1000;
var value = doCalculationForSeconds(passedSeconds);
document.getElementById('myDisplay)'.textContent = value;
}, 1000);
which calls this method every second.
Lastly, you need to figure out a good way to calculate the progress. You could either run your formula in a big loop for all of passedSeconds. Or you evaluate if you can reduce it to a single calculation step. Will depend on the exact changes in value you'll have in your final version.

javascript code execution time [duplicate]

This question already has answers here:
How to measure time taken by a function to execute
(30 answers)
Closed 8 years ago.
I just wanna know,how I can get the execution time of my javascript code.For example I have any javascript code(loop,function etc..) I wanna know how much time takes to executing it.Or test my code how many operations it makes for example per second or minute.
to calculate execution time use console.time (dev tools):
console.time("test");
//execute your code here
console.timeEnd("test");
you can do:
var startFrom = new Date().getTime();
//measured code here
console.log(new Date().getTime() - startFrom);
You should try using a profiling system. If you use Google Chrome, for example, can hit ctrl-shift-i (Windows) or alt-command-i (OS X) and click on the Profiles tab. You can then select the Collect Javascript CPU Profile radio button and then hit start.
You'll find a bit more information here: https://developer.chrome.com/devtools/docs/cpu-profiling
The only thing I know about is Date:
var start = new Date().getTime(); //Time in ms
doSomething();
var end = new Date().getTime();
console.log("Operation took "+(end-start)+" miliseconds.");
But I suppose every browser has it's profiler allowing you to get more info. At least in firefox, there's a profiler if you press Ctrl+Shift+I. I nevr used it, so you must try it yourself.

Categories