Can someone explain how the setInterval counter works? - javascript

I created a var for a setInterval so I can stop it with clearInterval as such:
var repeat = setInterval(sayHello, 2000);
function sayHello() {
alert("Hello");
}
and here is the clearInterval:
clearInterval(repeat)
Now, in Firefox, once I ran this bit, if I want to know the value of "repeat", it returns the amount of time the interval ran. However, in Chrome, no matter how many times it ran, it always returns 1. Unless, I do the entire procedure over, it then return 2. It basically increments the instances as opposed to interval occurrences.
Anyone able to shed some light on this, how it works, and why...greatly appreciated!

All that is guaranteed is that setInterval will return a handle which can then be used by clearInterval. Other than that it is entirely up to the browser what that handle is and how it is used. Even if it seems to provide some information in one particular browser, that should not be relied on in any way as it will be subject to change.
To quote MDN:
The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to WindowOrWorkerGlobalScope.clearInterval() to cancel the timeout.
Don't expect it, or rely on it, to be anything else.

Related

why do I set a variable for generator after setting a variable for a generator again ? (This case is different from ordinary generator examples)

After setting a variable for a generator like
let gene = generator();
Normally, What I need to do is
gene.next() to iterating the generator made above.
However, in this example below, (For the full code, please refer to the link)
https://codepen.io/jotnajoa/pen/MWwzpJJ
another variable is set after set a variable for the generator again.
I don't know why this is happening. Also, I don't get the part of
let result = genratorAnimation.next();
//genratorAnimation.next();
let interval = setInterval(function(){
if(!result.done) {
genratorAnimation.next();
}
else {
clearInterval(interval)
}
}, 50);
At the end of this code.
Because, to my understanding, generator returns 'true' for 'done' when everything is yielded.
However, in this example, it is doing the opposite thing. which is "not result.done" which is false while running the generator.
Why is it?
As a summary,
1) why do I need to set another variable for interval.
I assumed, setInterval( ######## ) is enough, instead of let xxx = setInterval to run the loop.
because, if I set the variable for setInterval,
nothing would happend till I type the variable 'xxx'. But in this code, it is running even if I do not call the variable.
2) Why !result.done makes the loop plays.
because !result.done is false and if false is within if statement, things comes after if wouldn't run.
If statement runs only when the condition is true.
Isn't it?
Thank you in advance.
why do I need to set another variable for interval.
setInterval() is used to repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. this means that the function provided to setInterval() function will be called and executed forever if its not stop by calling clearInterval() function.
clearInterval() require a interval reference (variable), in this snippet we can have the code without clearing the interval but it will keep running and consume resources memory/CPU with no effect in the end so its better to remove it from the execution queue.
Why !result.done makes the loop plays.
The generator function will keep returning result.done as false until its last result returned, it will return true: and ! (Logical NOT) used to negate a Boolean value so if result.done is false, !result.done will negate it and make it true. the way its written in your code snippet, is a matter of coding style it can be written as:
let result = genratorAnimation.next();
//genratorAnimation.next();
let interval = setInterval(function(){
if(result.done) {
clearInterval(interval);
}
else {
genratorAnimation.next();
}
}, 50);

What does using clearInterval method accomplish that setting an interval variable reference to null does not?

I have a reset method in a JavaScript service file that resets all variables in the service to null. Some of the variables hold interval timer references. I noticed that using the reset method seems to cancel the intervals (that should not actually be the case, but it does appear to be in my Angular app).
My question is, does setting the interval reference to null have the same effect as formally clearing the interval with clearInterval(name)? Are there any technical differences I should be aware of?
var myInterval = window.setInterval(function () { console.log('interval fired'); }, 500);
// Are these two equivalent?
myInterval = null;
clearInterval(myInterval);
I notice that there seems to be a WindowTimers interface in the spec, and that is where the clearInterval method comes from. My guess is that calling clearInterval removes the named reference from some kind of list or array. If I set the timer to null, is it being left in the WindowTimers list as a null object that just can't be executed?
The interval timer "handle", or whatever you want to call it, is just a number. It identifies the timer to the runtime, but it's otherwise not anything special. The value sitting in a variable doesn't make the variable any more special than any other value, so resetting the variable to null has no effect on the timer at all.
You can open up your browser developer console and type this:
console.log(setTimeout(function(){}, 1))
and you'll see a number. Run it a few times and you'll see a sequence of increasing numbers.
Setting the myInterval variable to null will not stop the interval.
You can see that if you try that code in the Developer Tools in Chrome. Only after calling clearInterval the console.log calls stops.

Is there a way in javascript to see if a variable has a timeout assigned to it?

I'm currently using a loop that repeats itself every few milliseconds in my program. In this loop, it checks for a certain input, and if received, cancels another timeout. Essentially:
if (inputreceived && secondTimerRunning)
{
timerID2.clearTimeout();
secondTimerRunning = false;
}
However, those lines cause my loop to terminate. From what I can tell, it's because I am trying to clear a Timeout that doesn't exist. Is there a way to prevent this, or am I using Timeouts wrong?
The syntax for clearTimeout() is;
clearTimeout(timerID2);
It is a function which accepts the ID returned by setTimeout(); i.e. you don't call it on the ID returned.
clearTimeout will not error if the value you pass to it is not a valid ID.
For more info, see the documentation for clearTimeout() on MDC.
Use clearTimeout(timerID2) instead, timeouts are represented by a number identifier and clearTimeout is a global function that can be called directly.

setTimeout vs setInterval again

So I know that there are differences between setTimeout and setInterval, but consider these two code examples:
function myFunction(){
setTimeout('myFunction();', 100);
doSomething();
}
setTimeout('myFunction();', 100);
and
function myFunction(){
doSomething();
}
setInterval('myFunction();', 100);
Note that in the first example I call setTimeout at the begining of the function and then I doSomething. Therefore there is no extra delay from doSomething(). Does that mean that those two examples do exactly the same? Or is there even more subtle difference?
They're functionally about the same, but there are differences. One difference is in how browsers handle it if doSomething takes longer than the interval. With setInterval, at least some browsers will just skip the next interval if doSomething is still running. So if you use 100ms as you have, and doSomething takes 110 ms to run, the next run won't happen until 90ms later (of course, all of these times are approximate).
Another difference is that with the setTimeout, you'll get a new handle every time, whereas with setInterval you get one handle.
Another difference with your examples as given is that in the setTimeout example, you're firing up a JavaScript parser/compiler every time, whereas with setInterval you're only firing up the parser/compiler once. But this difference shouldn't matter, because you shouldn't be doing that at all — see below.
But subtleties aside, what you have there is functionally the same.
Side note: It's not best practice to pass strings into either setTimeout or setInterval. Instead, pass in a function reference:
// setTimeout
function myFunction(){
setTimeout(myFunction, 100);
doSomething();
}
setTimeout(myFunction, 100);
// setInterval
function myFunction(){
doSomething();
}
setInterval(myFunction, 100);
Passing in a string fires up a JavaScript parser and does the same thing as eval. It should be avoided whenever possible (and it's almost always possible).
T.J. Crowder explained the main differences, one other more subtle could appear (I change the time scale as it's easier to explain) :
Lets plot the difference with a very big timeout time : 1 Day. You call both methods at 00:00 on Day 1 and let it run for 1 year...
1 Year latter your method called by setInterval will execute at 00:00 + some milliseconds (because you may not be the only one asking for the processors to do things at this exact moment and the OS timers have granularity anyway).
But your setTimeout method will occur latter, maybe around 00:01 because each day it would have been called a little after the requested time and requested to be called the next day at the same time...
PS: It could also be called before the requested time in some cases but more often than not it run after :-D

Does a this setTimeout create any memory leaks?

Does this code create any memory leaks? Or is there anything wrong with the code?
HTML:
<div id='info'></div>
Javascript:
var count = 0;
function KeepAlive()
{
count++;
$('#info').html(count);
var t=setTimeout(KeepAlive,1000);
}
KeepAlive();
Run a test here:
http://jsfiddle.net/RjGav/
You should probably use setInterval instead:
var count = 0;
function KeepAlive() {
$('#info').html(++count);
}
var KAinterval = setInterval(KeepAlive, 1000);
You can cancel it if you ever need to by calling clearInterval(KAinterval);.
I think this will leak because the successive references are never released. That is, the first call immediately creates a closure by referencing the function from within itself. When it calls itself again, the new reference is from the instance created on the first iteration, so the first one could again never be released.
You could test this theory pretty easily by changing the interval to something very small and watch the memory in chrome...
(edit) theory tested with your fiddle, actually, I'm wrong it doesn't leak, at least in Chrome. But that's no guarantee some other browser (e.g. older IE) isn't as good at garbage collecting.
But whether or not it leaks, there's no reason not to use setInterval instead.
This should not create a leak, because the KeepAlive function will complete in a timely manner and thus release all variables in that function. Also, in your current code, there is no reason to set the t var as it is unused. If you want to use it to cancel your event, you should declare it in a higher scope.
Other than that, I see nothing "wrong" with your code, but it really depends on what you are trying to do. For example, if you are trying to use this as a precise timer, it will be slower than a regular clock. Thus, you should either consider either setting the date on page load and calculating the difference when you need it or using setInterval as g.d.d.c suggested.
It is good to have setInterval method like g.d.d.c mentioned.
Moreover, it is better to store $('#info') in a variable outside the function.
Checkout http://jsfiddle.net/RjGav/1/

Categories