Work with Time in Javascript

Can anybody show me a piece of javascript code on how to know how much time a visitor spends on my website or on a post on my website. this is hypothetical I dont have my website yet. thank you.

Sure, very naïvely:

function createTimer () {
  let startTime, currentTime;

  return {
    start() {
      startTime = new Date();
    },
    getDuration() {
      currentTime = new Date();
      return currentTime - startTime;
    }
}

let timer = createTimer();

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'visible') {
    timer.start();
  } else {
    console.log(timer.duration())
  }
});

However, because the user is closing the page (or switching tabs or something similar that hides that page), that’s the last thing that happens. The above snippet isn’t actually any use as it is, even though it does exactly what you’ve asked for.

What’s the purpose of this? Because I think you want something slightly different or something in addition to what you’ve asked about.

1 Like

what do you mean by saying: The above snippet isn’t actually any use as it is.

I am thinking of creating a social network in the future after I finish the freecodecamp courses. I have an idea that may be genius for readers and writers. i am curious about how much time would they spend on reading somebody else’s post as that may be useful in the future.

it’s just showing it, for it to be useful it would need to be stored somewhere

1 Like

Yes, as @ilenia says it needs to be stored somewhere.

You asked for an example of JS code that shows how long someone has been on a site: that’s exactly what the above snippet does, assuming that someone goes to the web page, then leaves the web page. It’s just that, the thing you’re asking for, on its own, isn’t very useful. So for example:

Seeing how long they have the web page open doesn’t really tell you this.

If you want to figure out how long someone spends reading a post, how are you going to tell that?

I’m trying to suggest that you need to think a bit more carefully how you measure these things, or just what you measure, it’s an inherently hard problem [edit: it involves making educated guesses, and it’s difficult to check whether those guesses are valid].

Analytics is the obvious thing you could use, Firebase for example.

1 Like

so you are saying that i can not do what I want with javascript alone. should I use a different code language to solve that problem ? and can I use Firebase in my website directly or should I buy it?
thank you for what you explained so far, it opened some understanding of code language possibilities.

you need a full stack app, continue with the freeCodeCamp courses, you will have more knowledge with that

will do, thanx for making it available and free.

last but not least, can i store or assign that information (how much time is spent on a page) to a variable in my code so I can do operations on it or build a function upon it?
i hope I’m not bothering.

No. Not at all.

For example, you could show the user how long they have been on the page.

And you can use other JS APIs on the web page (so, for example, that last function call to time.duration could be navigator.sendBeacon(/SOME-URL/, time.duration()), but that “SOME-URL”, that’s got to be an actual URL you can send data to.

The JS that executes on a webpage, it’s only the person using the browser who it executes for. So if you want to store things that the user does, you need to get them to send those things to a server (a computer) you own (or are using).

Anything you want off the user, they have to send from their computer to yours (and they have to agree to do that, or at least you should ask them, it’s polite, even in situations where you can technically get information off them, legally, without asking)

So, for example, Firebase Analytics is a Google service where you add a script to your website, and on the Google side you have an account you can log into and set various analytics for that site up.

Same as above, but instead of writing some JS to do it, you add a script, and it handles sending data to Google, whose server it is you are using

2 Likes

I pasted this code on visual studio and it says I have to remove unreachable code. I am not at a level to read the code properly yet it says that it may not work.

There’s a missing curly bracket in the function

Capture0

when i click on those 3 dots it says this :slight_smile:
Unreachable code detected.ts(7027)

Property ‘duration’ does not exist on type ‘{ start(): void; getDuration(): number; }’.ts(2339)

there is a missing curly bracket, as Dan just said above

function createTimer () {
  let startTime, currentTime;

  return {
    start() {
      startTime = new Date();
    },
    getDuration() {
      currentTime = new Date();
      return currentTime - startTime;
    }
// Missing curly bracket here
}
1 Like

i added the curly bracket.
so I shouldn’t worry about those 3 dots under .duration, because they are still there.

what does it say now?

it says :

Property ‘duration’ does not exist on type ‘{ start(): void; getDuration(): number; }’.ts(2339)

any

It was just done as a quick example, I apologize for the small mistakes, but I wasn’t expecting you to just copy paste it. The error says there isn’t a function called duration. There isn’t. So how would you fix it?

1 Like

i apologize in advance too for taking your time but I am not in the level of understanding that code completely because I have just started javascript on freecodecamp. i am not into functions yet. see I was taking courses on codeacademy years ago then it was monetized so I lost interest in coding for years till I came across freecodecamp .
here in Morocco the cost of coding lessons is high +they teach them in French which is unnecessarily harder to learn. so I am like at the beginning again.

look it doesn’t matter i just want to save that code for later and i want it to be functioning. i’ll learn how it’s done further.