I need to collect data for statistics that people did for each visit to the site. Those. A person came to the site, he was given the visit id, which is saved only for a while while he is walking around the site. And when traveling around the site, the visit id and some data are sent to the database, the names of the pages visited and some more data.

In the script below, according to my logic, a timer is started to check for the presence of cookies with the visit id, if there is no cookie, then set the visit id and write it to the cookie, if there is a cookie, then take it from the cookie and overwrite the cookie.

What is wrong doing?

My code is:

// Ѐункция установки id Π²ΠΈΠ·ΠΈΡ‚Π° ΠΈ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ нахоТдСния Ρ‡Π΅Π»ΠΎΠ²Π΅ΠΊΠ° Π½Π° сайтС function check_vicit_id() { if (!getCookie(VISIT_ID_COOKIE)) { var date = new Date; date.setTime(date.getTime()+(5*1000)); visit_id = rand(1111111, 9999999)+"."+date.getTime(); // Π³Π΅Π½Π΅Ρ€ΠΈΡ€ΡƒΠ΅ΠΌ ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹ΠΉ visit_id посСтитСля document.cookie = ""+ VISIT_ID_COOKIE + "="+ visit_id +";expires="+ date.toGMTString() + "; path='/'"; console.log( 'ID VISIT: ' + visit_id); } else { var date = new Date; date.setTime(date.getTime()+(5*1000)); visit_id = getCookie(VISIT_ID_COOKIE); document.cookie = ""+ VISIT_ID_COOKIE + "="+ visit_id +";expires="+ date.toGMTString() + "; path='/'"; console.log( 'ID VISIT: ' + visit_id); } } function check_vicit() { setInterval(function() { check_vicit_id (); }, 1000); } 
  • And what you specifically fail? - Zhukov Roman
  • You showed the declaration of two functions. and you call check_vicit in the end? or is it all your code? - Ivan Pshenitsyn
  • offtop: visit, not vicit. - Ivan Pshenitsyn
  • I will correct about vicit! no, this is not all code, the rest of the code is not needed in principle, the check_vicit () function is launched there; - Alexander Sizintsev
  • @ZhukovRoman, but saving a cookie until a person leaves the site, i.e. Traveling around the site is first assigned normally, and then at the next transition, the id jumps up and another is assigned. I somehow need to do so that the id is preserved as long as the person is on the site. - Alexander Sizintsev

1 answer 1

In general, the code is correct, I did not find any problems except one: you expose cookies to a too short lifespan, 5 seconds. I think they quite really have time to become outdated between page transitions, especially if this code is located in your document.ready (or window.onload). Set at least 60 seconds. Less is already doubtful. On mobile devices, the load time for a page may well be several tens of seconds.