Chandler_bing_26
Chandler_bing_26

Reputation: 73

How to refresh particurlar element in javascript

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

Answers (5)

Nisal Edu
Nisal Edu

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

Roman
Roman

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)

Why pass in a Reference

The reference can be execute inside a function

Example

function logMe() {
  console.log('Hi :o')
}

function logMeToo() {
  console.log('Bye')
}

function messageLogger(youFunction) {
  youFunction()
}

messageLogger(logMe)
messageLogger(logMeToo)

Code

function abcd() {
  var date = new Date();
  document.body.innerHTML = "<h1>Today is: " + date + "</h1>";
}

setInterval(abcd, 1000);

Upvotes: 0

MSQ
MSQ

Reputation: 479

You can use the following code while calling the function:

setInterval(function(){
 abcd();
}, 1000);

Upvotes: 0

Vishal Chaurasia
Vishal Chaurasia

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

felixmosh
felixmosh

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

Related Questions