Function call using single quotes vs no quotes [duplicate] - javascript

This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 6 years ago.
The following pieces of code uses the function setInterval() to continually update a 'clock'. The only difference is in the function call setInterval().
When I change the setInterval argument from
setInterval('updateTime()',1000);
to
setInterval(updateTime(),1000);
[from single to no quotes], it does not work. Can anyone explain this to me?
Single Quotes:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval('updateTime()', 1000); //////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
No Quotes:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval(updateTime(), 1000);//////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
Online js console for testing can be found here: https://jsfiddle.net/

setInterval('updateTime()', 1000);
You are passing string to the setInterval as the first argument.You need to pass the function reference
Correct Way
setInterval(updateTime, 1000)

Try doing this
setInterval(updateTime, 1000);
without ()
Now coming to the question why.
The Setinterval function evaluates the content if string and executes if function name
To explain why it does execute the updateTime() with brackets immediately is because it tries to execute the output of the updateTime function in interval loop, that will be undefined if you are not returning anything and will be treated as function name if it returns a string. Anything else will be overlooked or error thrown.
Hope that helps

If you change your second code to
setInterval(updateTime,1000);
it should work. The reason is because ^there you're passing a function pointer to set interval while in your answer updateTime() is passing the return value of updateTime to setInterval.

Related

How do I set delays in template pasting scripts? [duplicate]

This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
Closed 2 years ago.
I am trying to make a script where while var < 1, it pastes letters, but it makes my screen crash. I tried seeing some questions here on StackOverflow, but the code doesn't line up with mine. I want the interval to be every 2 milliseconds
My code:
<template>
a
</template>
<html>
<head>a</head>
<body onLoad="pasteContent()">
</body>
<script>
while (true) {
function pasteContent() {
var i = 0;
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
}
</script>
</html>
Use setTimeout? Just set the timeout to 2 since it uses milliseconds.
Here's an article on it: https://www.w3schools.com/jsref/met_win_settimeout.asp
Use setInterval():
let div = document.querySelector('.div')
let intervalId = setInterval(writeLetter, 1000)
function writeLetter(){
if(div.innerHTML === 'aaaa'){
clearInterval(intervalId)
}else{
div.innerHTML += 'a'
}
}
<div class='div'></div>

Adding two number variables returns NaN

Working on a simple game, using delta time for the first time.
Delta time (dt) is created in this function:
function main() {
var now = Date.now();
var dt = (now - lastTime) / 1000.00;
update(dt);
render();
lastTime = now;
requestAnimationFrame(main);
};
gameTime (my second variable) is just created as a var.
var gameTime = 0;
The problem comes when I try to add dt to gameTime, here:
function update(dt){
gameTime += dt;
};
this returns NaN, whatever I seem to do to it. I can display gameTime, and add to it using ++, and I can display dt (0.017 usually), but as soon as I add one to the other, I get NaN.
How can I fix this?
Does your lastTime contain anything before running main() for the first time?
If not, then this code var dt = (now - lastTime) / 1000.00; can't work because lastTime is undefined
First of all, if you return you can see your result which is not NaN, basically you write it like this :
function update(dt)
{
return gameTime += dt;
};
Second of all,if you are not using this code in vanilla javascript and it's related to unity, try to initiate your variables. like how you defined var gameTime = 0;, check other variables and initiate them.

document.getElementById doesn’t work

If I write code 2 without code 1, the code works and it shows me “aaaaa”.
But if I write code 1 and code 2, the code doesn’t work. Instead of showing me “vvvaa”, it doesn’t show me anything (not “aaaaa” and not “vvvaa”).
Why doesn’t it work? (The document.getElementById doesn’t send the information to the <div>.)
Code 1:
document.getElementById('na').innerHTML = "vvvaa";
Code 2:
document.write("<div id='na'> aaaaa </div>");
Complete Code: (the only thing on the page)
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>
Order matters. You cannot access your element 'na' before having it in the document.
You naturally need to add the element to the document first. If that's done, you can access it by functions like getElementById().
This...
document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";
... will work.
You may shortcut this to:
document.write("<div id='na'>vvvaa</div>");
I am assuming your console says that document.getElementById('na') is undefined and innerHTML is not a method of undefined. This is caused by the fact that there is no such element when the code is called. A fatal error will stop any further javascript execution, in this case your document.write.
Add the element to your document first before trying to access it via document.getElementById
You can't access a piece of text unless it really does exist. In your case, you are trying to access the text when it doesn't even exist at that point. The order matters. Code 2 should go first and Code 1 should go last. First write the text, then access it.
The document.write only be passed after timeago() therefore does not exist over the <div>, so just call "timerago" after using document.write Try:
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
document.write("<div id='na'> aaaaa </div>");
timeago('1376743609');
</script>

Which is better between setTimeout and setInterval?

The following code is from 'JavaScript by Example Second Edition',I think the code below is better
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
}
setInterval(scroller, 300);
The old code is recursive and will continue to call itself every 0.3 seconds until the program ends, I think the old code maybe cause stack overflow, right?
<html>
<!-- This script is a modification of a free script found at
the JavaScript source.
Author: Asif Nasir (Asifnasir#yahoo.com)
-->
<head>
<script type="text/javascript">
var today = new Date();
var year = today.getFullYear();
var future = new Date("December 25, " + year);
var diff = future.getTime() - today.getTime();
// Number of milliseconds
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
// Convert to days
var str =
"Only " + days + " shopping days left until Christmas!";
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
setTimeout(scroller, 300); // Set the timer
}
</script>
</head>
<body onload="scroller()">
<b>
<font color="green" size="4">
Get Dizzy. Watch the title bar and the status bar!!
<br />
<image src="christmasscene.bmp">
</font>
</body>
</html>
setInterval is good if you don't care too much about accuracy, e.g. polling for some condition to be met.
setTimeout is good if you want a one–off event or need to adjust the interval between calls, e.g. a clock that should update as close as possible to just after the next whole second.
Both can be used for events that run continuously at approximately the specified interval, both can be cancelled, both only run at about (as soon as possible after) the designated time interval.
Incidentally, the first code example in the OP should not cause a stack overflow, though it is otherwise not very well written.
Have a look here:
'setInterval' vs 'setTimeout'
setTimeout runs the code/function once after the timeout.
setInterval runs the code/function in intervals, with the length of
the timeout between them.
For what you're doing, you should be using setInterval.

How to handle cookies in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the “best” way to get and set a single cookie value using JavaScript
I am working on a project where it requires to check cookie and tell whether it is 20 minutes old or not. So I have written once code which is like this.
This is only javascript code I have pasted.
function checkcookie()
{
var difftime= getcookie();
// further operation comes here
}
var cookieminutes;
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
if(start==-1)
{
cookiedate = new Date();
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
cookieminutes= cookiedate.getMinutes();
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}
In function getcookie the variable cookieminutes is coming as undefined. But as I know since it is a global variable it should have the value.
Can anybody please tell what is the solution for this.?
You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.
Try this:
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
cookiedate = new Date();
cookieminutes = cookiedate.getMinutes();
if(start==-1)
{
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}
If you want to use global variables (generally bad design) set and access them explicitly with window. E.g.:
window.cookieminutes = cookiedate.getMinutes();
and later:
document.write("Cookie minutes is "+window.cookieminutes);
And drop the var cookieminutes;
As I said in my comment, it looks like if getcookie is being called for the first time on a given page load, and the cookie exists (start != -1), cookieminutes is never set. You need to make sure you don't use undefined variables.

Categories