Javascript: Increment count by 5 for a variable inside a setInterval() function

百般思念 提交于 2019-12-20 06:27:30

问题


I'm trying to use Google Analytics events to track time spent on site more accurately (without relying on delta time between visits to another page on site). I'm using setInterval() to continuously trigger that GA even every 5 seconds. How do I properly increment seconds elapsed to send along with the GA event data?

  var count = 0;
  setInterval(function(){
    // increment "count" by 5 each time setInterval is run
    ga('send', 'event', 'time', 'tracking', 'seconds', count);
  }, 5000);

回答1:


  var count = 0;
  setInterval(function(){
    // increment "count" by 5 each time setInterval is run
    count+=5; //is this what you need?
    ga('send', 'event', 'time', 'tracking', 'seconds', count);
  }, 5000);



回答2:


Is this what your looking for?

var count = 0;
setInterval(function(){
  count = count + 5;
  // increment "count" by 5 each time setInterval is run
  ga('send', 'event', 'time', 'tracking', 'seconds', count);
}, 5000);



回答3:


How about this?

var count = 0;
setInterval(function(){
    count+=5;
    // increment "count" by 5 each time setInterval is run
    ga('send', 'event', 'time', 'tracking', 'seconds', count);
}, 5000);



回答4:


Not sure if I gather this correctly, but we can do this like: var count = 0,interval=5000; setInterval(function(){ // increment "count" by 5 each time setInterval is run ga('send', 'event', 'time', 'tracking', 'seconds', count+interval); }, interval);

In clear interval you can set count = 0 again.



来源:https://stackoverflow.com/questions/21942872/javascript-increment-count-by-5-for-a-variable-inside-a-setinterval-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!