set Interval in javascript - javascript

I am beginner in javascript.
There is strange thing in javascript and I feel stupid
//First statement
var myVar = "Hello";
function hello() {
document.getElementById("demo").innerHTML = myVar;
}
//second statement
var myVar = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById("demo").innerHTML = new Date().toLocaleTimeString();
}
Why the second function work without invoked it ?
Unlike the first ? This caused a lot of problems to me !

Why the second function work without invoked it ? Unlike the first ?
You are passing the function myTimer to setInterval. setInterval calls the function every 1000ms. So while it is not you who directly calls the function, it is still called (by setInterval). setInterval's whole purpose is to call the function that you pass to it as argument.
In contrast, you are not doing anything with hello. You are neither calling it directly, nor are you passing it to any other function that could call it.

From what I can gather from the comments, you seem to be confused as to why the myTimer() function works. Here's a brief explanation:
On this line
var myVar = setInterval(myTimer, 1000);
you are calling the setInterval() function. That function takes 2 parameters, which you have defined. The first one is a function; the code to be executed. The second one is the delay between each execution of said function.
On the next line, you have declared the variable myTimer to be a function which is executed with the setInterval.
Have a look at the MDN documentation for details. Specifically, it says:
var intervalID = window.setInterval(func, delay)
The parameters are defined as:
func: A function to be executed every delay milliseconds.
and
delay: The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code.

Related

How is setInterval invoked here?

I have the following Javascript code attached to an HTML document with some CSS styling.
It is simply a box on the screen that changes the style background property colour according to those seen in the array. The id of "colour-changer" is used to access the HTML document and changes it each time the array is iterated.
The function declaration changeColour(); is used to make this happen by using colours.length to count its way through the array and then puts the array value into the HTML, which changes its background colour every 3 seconds.
Once it comes to the end of the array the counter is reset to 0, and it continues around again.
The setInterval method invokes the callback method changeColour() every 3 seconds to make this happen.
In order to stop the cycle, an onclick is event is added which invokes a clearInterval() method to print out "Timer stopped" inside the box. In order to do this the setInterval() method had to be stored in variable myTimer.
See the code below. It all works fine but this is not my real problem.
let colourChanger = document.getElementById ("colour-changer");
let colours = ["red","blue","green","pink"];
let counter = 0;
function changeColour(){
if (counter >= colours.length){
counter = 0;
}
colourChanger.style.background = colours[counter];
counter++;
}
let myTimer = setInterval(changeColour, 3000);
colourChanger.onclick = function (){
clearInterval(myTimer);
colourChanger.innerHTML = "Timer stopped";
}
What I cannot understand is the line let myTimer = setInterval(changeColour, 3000);
From my understanding if you store a function inside of a variable, it will NOT execute unless called separately. It will just sit there stored in the variable myTimer.
There is no setInterval(); call made outside of the variable anywhere.
MY QUESTION:
How then is this method invoked since it is simply stored inside of the variable myTimer?
No, your understanding is wrong.
It executes setInterval(changeColour, 3000); and stores this particular interval reference ID to myTimer to later be used in clearInterval(myTimer)
var myTimer = setInterval(() => console.log('ping'), 3000);
setTimeout(() => clearInterval(myTimer), 10000);
console.log('myTimer value: ', myTimer);
In order to do this the setInterval() method had to be stored in variable myTimer.
No, the return value of setInterval is stored in myTimer by that code. setInterval is called (it has (/*...*/) after it, which calls it).
From my understanding if you store a function inside of a variable, it will NOT execute unless called separately.
That's correct, but that's not what that line of code is doing. This code:
let myTimer = setInterval(changeColour, 3000);
calls setInterval and stores its return value in myTimer, exactly the way:
let x = example();
calls example and stores its return value in x.
It's the changeColour function that is only referenced, not called, by that code (there's no (/*...*/) after it). Doing that passes changeColour into setInterval, so that setInterval knows what function to call every three seconds or so.
So in that code, setInterval is called, and changeColour is just referenced (it's called later by the timer mechanism).
setInterval() function will return IntervalID, It will set execution interval for given milliseconds.
In your case once this line is executed it will start executing changeColour function every 3000ms / 3 seconds and return IntervalID.
Now this IntervalID is used to stop executing your function every 3 seconds in the future.
to stop executing you can use clearInterval(IntervalID).
if any doubts please comment.

Why must a call to a function be enclosed in function()

Coming from a standard programming language, I find this snippet of javascript hard to understand:
(from http://www.w3schools.com/js/js_timing.asp)
var myVar=setInterval(function () {myTimer()}, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
Why is the call to myTimer() further enclosed in function(){}, it is a function. And isn't setInterval() expecting a function? So why not just refer to the function directly? as in:
var myVar=setInterval(myTimer(), 1000);
What I also don't understand is that the above actually runs once. Why is that? (If it is incorrect then it should not work at all)
Thanks
To pass the reference just use the function name without ().
var myVar=setInterval(myTimer, 1000);
When () is used the function is invoked and the returned value is passed to the setInterval
So why not just refer to the function directly? as in:
var myVar=setInterval(myTimer(), 1000);
Because then the result of myTimer call is passed. Functions aren't different to any other value when you pass them to other functions.

How exactly works the setTimeout() JavaScript method?

I am not so into JavaScript and I have the following doubt related the setTimeout() method.
So into a test script I have:
function simpleMessage() {
alert("This is just an alert box");
}
// settimeout is in milliseconds:
setTimeout(simpleMessage, 5000);
So when I perform the page, after 5 second the simpleMessage() function is performed and it is shown the alert popup.
I understand that when I do:
setTimeout(simpleMessage, 5000);
it means that the simpleMessage() function have to be performed after 5 second after the timer settings but why it is used simpleMessage and not simpleMessage() for the function invocation?
simpleMessage is a reference to a function whereas simpleMessage() executes the function. setTimeout needs a function reference to call a later time.
To perhaps make things a little more obvious, you could have written your function declaration as
// define my function (but don't execute it)
var myFunction = function() {
alert('SOUND THE ALARMS!');
};
// start a timer that will execute the given function after the given
// period of time
setTimeout(myFunction, 5000);
See setTimeout documentation.
The first argument to setTimeout is the function to be executed. The identifier simpleMessage refers to the function you want setTimeout to execute, so that's what you supply as an argument to setTimeout.
If you did setTimeout(simpleMessage(), 5000);, you would execute simpleMessage immediately and then setTimeout would get the return value as its first argument. This is comparable to:
var value = simpleMessage();
setTimeout(value, 5000);
This doesn't make sense; it is the same as setTimeout(simpleMessage(), 5000);.
Consider also a higher-order function that returns a function:
function funcFacotry() {
return function() { alert("this is just an alert box."); }
}
var simpleMessage = funcFactory();
setTimeout(simpleMessage, 5000);
In this case, this actually does make sense, because the return value of funcFactory is actually a function itself.
setTimeout in javascript executes the function after a specific amount of time set as the second parameter, while if you use with setInterval it will execute in intervals, without to consider if the function is get executed or not (this will lead to chunkiness for example if you ar using for animation).
As a metter of second question: if you are using the function with parentheses, this is a method invocation, while using without parentheses is a reference to a specific method.
Because you need to pass a reference to setTimeout of the function you want to invoke after the 5s.
This:
setTimeout(simpleMessage(), 5000);
would execute the simpleMessage function at the same time you're calling the setTimeout function.

Javascript variable not displaying in simple HTML script

I'm trying to have a simple html page that counts up indefinitely. But for some reason my second variable is not being displayed. The second variable is an embedded javascript timer As you can see the first variable is displayed, but not the second. Apologies, I'm a beginner.
https://dl.dropboxusercontent.com/u/44188718/time.html
<script>
var test;
test = 123;
</script>
<script>document.write(test)</script>
<script>
var time;
time = 0;
function startTimer()
{
window.setTimeout(add(), 60 * 1000);
}
add()
{
var += 1;
}
</script>
<script>document.write(time)</script>
Your middle script element contains several errors.
This line:
window.setTimeout(add(), 60 * 1000);
should be:
window.setInterval(add, 60 * 1000);
setTimeout() calls a function exactly once. setInterval() calls a function repeatedly. Also note that I've removed the () after add - with parentheses it calls the function immediately and passes its result to setTimeout() or setInterval(), but you want to pass the function itself so just use the function name with no parentheses. (And the window. part is optional).
Then this line:
add()
should be:
function add()
And this:
var += 1;
should be:
time += 1;
// OR
test += 1;
(I'm not sure which variable you intend to increment.)
Also you never call the startTimer() function.
Finally, in your add() function you'd need to actually output the value. document.write() is almost never a good idea, so I'd suggest creating an element on your page to hold the number and updating its content:
<div id="timer"></div>
document.getElementById("timer").innerHTML = time; // or = test; (whichever var you want)
Demo of all of the above: http://jsfiddle.net/Y3XMk/
Or the same effect with simplified code: http://jsfiddle.net/Y3XMk/1/
There are several misconsceptions in your code, so I will try to go through them.
You have to specify the function keyword when you define a function. In your case:
add(){ ... }
Should be:
function add() { ... }
Then you can safely call it from your setTimeout code.
Using the keyword var you are basically telling that you are about to define a variable for the current scope. First of all, since the current scope is window anyways (the global scope), you don't need to add var. Secondly, you have to use the variable name when you change it, or add to it. In your case:
var += 1
Should be:
time += 1
Functions get called once, when you call them. In your case, document.write(time) will get called once when the document is parsed, and hence will write 1 in your document. You have to call the write method inside your add function, to have numbers show up at every interval. So:
function add(){
time += 1;
document.write(time);
}
setTimeout calls the specified callback function once, after the time is passed, I believe you are looking for setInterval. You can use it like so:
function startTimer(){
window.setInterval(add, 60 * 1000);
}
But don't forget to call your function, in order for the timer to start.
Here is an example of your code (it works every second instead):
Working fiddle
There are a lot of things wrong with your code.
I believe what you are trying to do is this:
<script>
var time = 0;
window.setInterval(function(){
document.write(time);
time++;
}, 60*1000);
</script>
See a working demo here:
http://jsfiddle.net/8MVFB/
Just click "Run".

delcare a function?

i wonder what the difference is between these two declarations:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function delay {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
}
The first function declaration uses an anonymous function to create a closure over the variable timer and a second anonymous function to avoid polluting the global namespace with timer. This is a simple and handy technique to implement data hiding and static variables within a function in JavaScript.
This first/outer function typically only gets used once, which is why it is never given a name, but instead is executed immediately as an anonymous function. However, the opposite is true if you needed to be able to create multiple timers for multiple events.
Consider the following:
var delayBuilder = function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
}
Now:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
is equivalent to:
var delay = delayBuilder();
So, if you needed to have multiple delays (more than one timer running at the same time), you could do:
var delay1 = delayBuilder(),
delay2 = delayBuilder(),
...
delayN = delayBuilder();
// And of course, used as:
delay1(callback, ms);
More generalized, you have a function to build functions, in other words funcBuilder and func (using "func" since "function" is a reserved word).
var func = funcBuilder(configurationifany);
So, if the function builder was more complex and you wanted a single, throw-away instance of whatever function it was building, you could do
funcBuilder(configurationifany)(etc, etc);
Or in the case of the code that you posted (although this is overkill for simply wrapping setTimeout but just to continue the example):
delayBuilder()(callback, ms);
It really boils down to usage. If you're not going to use the function builder more than once, there's no sense in keeping it around and executing it as an anonymous function is more appropriate. If you need to build multiple instances of that function, then saving a reference to the function builder makes sense.
The purpose of having a function return another function is to create a scope for variables declared outside the function without having to declare them globally. The outer function is executed immediately after it's created (by putting the parentheses after the declaration), so the inner function is returned and assigned to the variable.
In the first example the timer variable is used in the inner function, so a closure is created that contains the variable. When you later use the function, it still has access to the timer variable although it's not inside the function itself. The outer function is executed so that it returns the inner function, and it's assigned to the delay variable.
Discussing the difference between the two declarations is pointless. The second declaration only declares the outer function, but then it's neither stored nor executed so it's just thrown away.
Edit:
In your updated question (if corrected by adding parentheses efter the function name in the second declaration), the second declaration is a function that returns the same result that is assigned to the variable in the first declaration. So to get the same result you have to call the function and assign the return value to a variable:
var d = delay();
Now the d variable contains the same as the delay variable in the first example.
In the second case you discard the returned function.
If I understand your question right, that is if you want the second case to be
function delay() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
}
then the difference is that the code stored into delay is not executed. If you call delay later, then it will be equivalent and the difference would be anonymity of the function and the value of delay (in the first case it's inner function, in the second - outer one).
In the first case, you create then call an anonymous function. In the second, you create an anonymous function but neither call it nor save it in a variable. I'm not even sure that's legal.
The first case uses a function expression to generate an anonymous function, which is called instantly and which wraps a timer variable in a closure and returns another function (generated with a function expression).
The second case is a syntax error (since there is no context for a function expression and no name for a function declaration).
Since you have now edited it…
The second case now uses a function declaration, but doesn't call the function. So it will now do what the anonymous function does (and not what the returned function does).

Categories

Resources