0

In this, I am trying to assign the start time in the beginning and when I will click on the page it should return me the time spent but I am getting 0 always. I am not understanding that where I might have gone. Need your help.

 var timeSpent = (function(){ var time = new Date(); var timeRun = false, startTime = time.getTime(); return function(){ // call this function by timeSpent()(); return time.getTime() - startTime; } })(); addEventListener("click", function(){ console.log(timeSpent()); }) 
3
  • 1
    time and startTime are the same time. The instances of Date aren't live, they contain the time which was current at the time the instances were created. Commented Oct 10, 2018 at 9:13
  • In this I want that startTime get its value assigned at the time of start of page and when the function runs again then I get the difference between the time when user entered the page and clicks on the page. Commented Oct 10, 2018 at 9:15
  • @PraveenKumarRana — Then you need to replace time.getTime() (which is when the user entered the page) with the current time Commented Oct 10, 2018 at 9:16

3 Answers 3

1

You need to calculate the present time inside the inner function

var timeSpent = (function(){ var time = new Date(); var timeRun = false, startTime = time.getTime(); return function(){ // call this function by timeSpent()(); return (new Date()).getTime() - startTime; } })(); addEventListener("click", function(){ console.log(timeSpent()); })

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

Comments

0

time is a date. Every time you call getTime() on it, you will get the same value.

So startTime and time.getTime() will always be the same.

You need to replace time.getTime() inside the returned function with something which will get the current time. (new Date()).getTime()

var timeSpent = (function() { var time = new Date(); var timeRun = false, startTime = time.getTime(); return function() { // call this function by timeSpent()(); return (new Date()).getTime() - startTime; } })(); addEventListener("click", function() { console.log(timeSpent()); })

Comments

0

Your function timeSpent() is evaluated as (you can check it by logging the function in console)

return time.getTime() - startTime;

As, startTime = time.getTime() initially. Therefore, the above return statement will evaluted to 0. In order to get the current time, you will have to call new Date().getTime()

var timeSpent = (function(){ var time = new Date(); var timeRun = false, startTime = time.getTime(); return function(){ // call this function by timeSpent()(); return new Date().getTime() - startTime; } })(); addEventListener("click", function(){ console.log(timeSpent()); })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.