0

I want to have a live update on how many seconds have I started working on something. So I used recursive function to call itself. But however when I run, there seems to be an error as it is not updating. Following is my code:

        getDiff();
        function getDiff(){
                var date1 = new Date("04/06/2011");
                var d = new Date();

                var month = d.getMonth()+1;
                var day = d.getDate();

                var date2 = new Date($.now());;
                var timeDiff = Math.abs(date2.getTime() - date1.getTime());
                var diffDays = 0;

                // seconds
                $("#webSeconds").html(Math.ceil(timeDiff / (1000))+" seconds"); 

                 setInterval(getDiff(),5000);
        }

As you can see, I am using setInterval but nothing is happening, any advice?

5
  • When is 04/06/2011? Is that 4 June or 6 April? Parsing strings with the Date constructor (which calls Date.parse) is almost entirely implementation dependent and notoriously unreliable. Commented Oct 18, 2014 at 14:09
  • What you want is setTimeout(getDiff, 5000) (which schedules the function, but does not call it). Notice that your current code does recursively call the function, unfortunately with no end. Commented Oct 18, 2014 at 15:43
  • Thank you for the suggestion @RobG. What would your reccomendation be? Commented Oct 18, 2014 at 15:50
  • @bergi yes thanks, that is the solution. And yes there is no end Commented Oct 18, 2014 at 15:51
  • @RickyHalim—if you wany 4 June, then new Date(2011,5,4) noting that months are zero indexed so 5 is June. Commented Oct 19, 2014 at 11:43

1 Answer 1

1

When passing the function in the setInterval call, don't use parenthesis after the function name. By using parenthesis, you are immediately calling the function, and passing its return value (in this case undefined).

setInterval(getDiff,5000);
//                 ^ no ()

This isn't limited to the use of setInterval, in JavaScript any time you need to pass a function as an argument or assign its reference to a variable, it shouldn't include the parenthesis.

Sign up to request clarification or add additional context in comments.

3 Comments

Ahh that did the trick! Thanks! However what if i need to pass some parameters then?
To pass arguments you can use .bind like getDiff.bind(this, param1, param2, param3).
You can pass a function like setInterval(function(){getDiff(arg0, arg1, ...)}, interval). Also, calling setInterval recursively will start a new timer each time so after about 20 seconds there will be 4 running.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.