Reputation: 73
I am trying to display the date and simultaneously refresh it to show each second
Where did I go wrong?
<script>
function abcd(){
var date = new Date();
document.body.innerHTML = "<h1>Today is: " + date + "</h1>";
}
setInterval(abcd(),1000);
</script>
Upvotes: 3
Views: 167
Reputation: 7591
Try as follows use abcd instead of abcd()
function abcd(){
var date = new Date();
document.body.innerHTML = "<h1>Today is: " + date + "</h1>";
}
setInterval(abcd,1000);
Upvotes: 0
Reputation: 5230
The difference between abcd
and abcd()
is that the first is a reference and the second will return a value (in your case undefined
)
The reference can be execute inside a function
function logMe() {
console.log('Hi :o')
}
function logMeToo() {
console.log('Bye')
}
function messageLogger(youFunction) {
youFunction()
}
messageLogger(logMe)
messageLogger(logMeToo)
function abcd() {
var date = new Date();
document.body.innerHTML = "<h1>Today is: " + date + "</h1>";
}
setInterval(abcd, 1000);
Upvotes: 0
Reputation: 479
You can use the following code while calling the function:
setInterval(function(){
abcd();
}, 1000);
Upvotes: 0
Reputation: 98
when you write setInterval(abcd(),1000), then the function abcd is invoked immediately and the return value of abcd is passed which is undefined in this case so actually you are writing setInterval(undefined, 1000) because of which your code doesn't work as expected. Just pass the name of the function.
Upvotes: 1
Reputation: 35563
As @gurvinder372 mentioned, the interface of setInterval
function is a function and an integer.
You need to pass the function itself and not the invocation of it.
function abcd() {
var date = new Date();
document.body.innerHTML = "<h1>Today is: " + date + "</h1>";
}
setInterval(abcd, 1000);
Upvotes: 0