setInterval time not precise [duplicate] - javascript

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.

Related

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

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>

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 incrementally faster [duplicate]

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 5 years ago.
Given a setInterval, can its timer keep getting quicker?
Such as that the code to be ran starts at 2 seconds, then 1.9s, 1.8s, 1.7s, etc...? (at this point I'm not worried about reaching zero or negative.)
I currently have:
let speed = 2000;
let timer = setInterval(function() {
display();
faster();
console.log(speed)
}, speed);
function faster() {
speed -= 100;
}
function display(){
// displays another square on canvas
}
I ask if it is possible because the console.log shows that the speed does indeed decrease, but the display function is not being called at faster intervals; it is always being called every 2 seconds. Therefor the speed of the setInterval is not getting faster....
No. The setInterval() rate is fixed at the value of the second argument when the timer is started.
You can use setTimeout() instead, reestablishing the timer upon each invocation of the callback:
var rate = 100;
setTimeout(function callback() {
// do something
setTimeout(callback, rate - 10);
});

JavaScript setInterval and setTimeout timing issue [duplicate]

This question already has answers here:
Is there a more accurate way to create a Javascript timer than setTimeout?
(16 answers)
Closed 7 years ago.
Please see the following JavaScript code:
var cis_current_time = 0;
setInterval(function() {
cis_current_time += 1;
},1);
$("#timingInfo").html(cis_current_time);
setTimeout(function() {
$("#timingInfo").html($("#timingInfo").html() + ', ' + cis_current_time);
},1000);
As a result I except to get 0, 1000, but it returns 0, number near 200
Please check a fiddle.
What is the reason of such behavior?
setInterval and setTimeout may not be precise due to their design.
They are executed by the browser engine, which means the browser can throttle them in some cases. Just for an example, if your browser just uses one process for the JavaScript, they can be throttled or maybe elapse more ticks than you define, due to current pressure on your used core.
It can be improved a bit by using a multithreaded JavaScript, but anyway - they won't be 100% accurate.
setInterval only guarantees a new execution/call after the given time period. Not at the exact time. There may be differences each interval at all.
setInterval function is very precise, as you can see on this fiddle.
Problem is in your code, you are trying to execute a function each milliseconds.
setInterval(function() {
cis_current_time += 1;
},1);
JavaScript is monothreaded, then, when it has a lot of instructions, it stacks them and call them when it has the possibility, so, that's why it is not precise in your case.
setInterval is not the problem, JavaScript is : JS executes functions when it can, that's why it is executed later... Every function is concerned by this problem, so setInterval too...
Func(1) taking 70ms :
If Func(1) is taking 130ms :
setInterval is precise but has the same problem than each function in JS.
Image credits

setInterval 'stacking' up [duplicate]

This question already has answers here:
javascript animation queueing when page does not have focus
(3 answers)
Closed 8 years ago.
Using setInterval to run a function which gives a 'flash' effect to a list.
If I keep the page open, but visit another tab / come back in 10 minutes or so, the setInterval feels like its working every 1 seconds as the function is constantly being called.
Feels to me like its stacking up over time, anyway to fix this?
function flashListItems(){
$('.imageview_navigation li').each(function(i) {
$(this).delay((i++) * 100).fadeTo(200, 0.8).fadeTo(200, 1);
});
}
setInterval(function(){
flashListItems();
}, 10000);
fiddle: http://jsfiddle.net/6w6wrsm0/
There's nothing wrong with your code, some web browers slow these types of intervals down to not cause too much usage. So when the webpage is not used, the fastest a interval can go is usually about 1 sec.
There might be a way to fix this, which is mentioned here:
How can I make setInterval also work when a tab is inactive in Chrome?
Just make your animation function tick by real elapsed time.
var div = $('#my-div');
var leftValue = 0;
var interval = (1000/20); //20fps
var before = new Date();
setInterval(function()
{
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if(elapsedTime > interval)
{
//Recover the motion lost while inactive.
leftValue += Math.floor(elapsedTime/interval);
}
else
{
leftValue++;
}
div.css("left", leftValue);
before = new Date();
}, interval);

Categories