Javascript variable not displaying in simple HTML script - javascript

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".

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.

Attempting to generate HTML in vanilla JS using document.write, then access the tags using .getElementById [duplicate]

I need to run a javascript function each 10 seconds.
I understand the syntax must work like follow but I am not getting any success:
function funcName() {
alert("test");
}
var func = funcName();
var run = setInterval("func",10000)
But this isn't working. Any help?
A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.
Your code, for reference:
function funcName() {
alert("test");
}
var func = funcName();
var run = setInterval("func",10000)
Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.
When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.
So, when you say:
var func = funcName();
You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.
Then you have this line:
var run = setInterval("func",10000)
The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.
However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:
func
// 10 seconds later....
func
// and so on
However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.
The solution is to give setInterval a function to run instead of a string. So, in this case:
var run = setInterval(funcName, 10000);
Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.
So, another solution for your code would be:
var func = funcName;
var run = setInterval(func, 10000);
However, that's a bit redundant: why use func instead of funcName?
Or you can stay as true as possible to the original code by modifying two bits:
var func = funcName;
var run = setInterval("func()", 10000);
In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.
Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.
setInterval(function () {
alert("test");
}, 10000);
In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.
Change setInterval("func",10000) to either setInterval(funcName, 10000) or setInterval("funcName()",10000). The former is the recommended method.
That's because you should pass a function, not a string:
function funcName() {
alert("test");
}
setInterval(funcName, 10000);
Your code has two problems:
var func = funcName(); calls the function immediately and assigns the return value.
Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
Btw this didn't work
setInterval(function () {
alert("test");
}, 10000);
I had to give a name (whatever you like) to the anonymous function:
setInterval(function alertNotification () {
alert("test");
}, 10000);

set Interval in 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.

Different behaviour between inline and non-inline JavaScript

I am trying to build a timer. Please compare the two situations (the first one works, not the second):
inline javascript http://jsfiddle.net/x7xhA/
non-inline javascript http://jsfiddle.net/x7xhA/1/
What is the problem?
This is a commonly encountered problem with users of jsFiddle's 'JavaScript section'. You see, the code that's put into the 'JavaScript section' is wrapped within a function used as a load handler, so in your second example, the real output result is this:
<script type='text/javascript'>
//<![CDATA[
$(window).load(function(){
var seconds = 0;
function timedCount() {
$("#txt").val(seconds);
seconds += 1;
setTimeout("timedCount()",1000);
}
});
//]]>
</script>
Now, timedCount isn't a global function anymore, as it's available in the scope of the load handler only, and when you use setTimeout with a string of code, this gets evaluated from the global scope.
Ways to fix this include:
change the setTimeout call to setTimeout(timedCount, 1000);
What this does, is passes the actual function object to setTimeout. Rather than evaluate the string of code, from global scope, each time, this essentially preserves the ability to call the function as scope doesn't matter anymore - you're handing the function to setTimeout.
var seconds = 0;
function timedCount() {
$("#txt").val(seconds);
seconds += 1;
setTimeout(timedCount,1000);
}
make timedCount a global function using timedCount = function() { ... };
This merely makes timedCount a global, so that when setTimeout tries to evaluate timedCount(); from the global scope, it succeeds as there is a timedCount function in the global scope.
var seconds = 0;
timedCount = function() {
$("#txt").val(seconds);
seconds += 1;
setTimeout("timedCount();",1000);
}
The second one wraps the timedCount function in jQuery ready function, hence is not available in global scope.
Fixed: http://jsfiddle.net/x7xhA/2/

How to figure out how to use setInterval correct with this jQuery script

This is a continuation of a previous question I asked.
I'm trying to display a clock based on a pre-determined time value .. not the current clients time.
Here's my jQuery:
$(document).ready(function () {
var currentTime = new Date('3/09/2010 9:27:29 PM');
setInterval("DisplayTime(currentTime, $('.answer-body'))", 1000);
})
function DisplayTime(currentTime, destination) { ... }
Now inside the DisplayTime function, i was showing some custom text, calling the destintion.html(..) to display that custom text. And finally, after I display the text, I was thinking of adding 1 second to currentTime so when the next iteration of the interval, it's not using the original time value, but 1 second later.
Problem: I cannot pass in the currentTime variable to the setInterval function. I don't particularly want to have an anonymous function here, unless I have no choice.
How can I refactor my bad code?
So every second, the time is re-displayed with the new second being added.
On the contrary, you should use an anonymous function here, like this:
setInterval(function() {
DisplayTime(currentTime, $('.answer-body'));
}, 1000);
Don't ever pass a string to setInterval() or setTimeout() if you can avoid it, it performs an eval() and has scope issues, like the one you're currently experiencing, since currentTime isn't a global variable.
$(document).ready(function () {
var currentTime = new Date('3/09/2010 9:27:29 PM');
var destination = $('.answer-body');
function DisplayTime()
{
destination.html(currentTime);
currentTime.setTime(currentTime.getTime() + 1000);
}
var id = setInterval(DisplayTime, 1000);
})
This uses a function (closure) within a function, but not an anonymous one. DisplayTime will not be accessible from outside scopes. There's no real reason to dislike anonymous functions, used appropriately. I would use one here.

Categories

Resources