call javascript function for every nth user
-
27-10-2019 - |
Question
I am collecting some sample data on my site and for now just want to collect data from say 10% of my visitors using a javascript function.
One way I can think of is to pick a number between 1 to 10 randomly and if its 10 then call the JS function to collect data else do nothing.
Also the data set need not be exactly from the 10% of users but a approximate number would also do for me.
I am Looking for suggestions on an alternate or better way to accomplish this.
Solution
You could keep a server side counter (in a DB for example) that checks before it delivers the page - if the counter is divisible by 10 then it includes the Javascript in the template, otherwise, the Javascript is omitted.
Of course, this is a very generic answer - how easy this would be to implement completely depends on your knowledge of server side scripting and the framework of your site.
OTHER TIPS
I would do something like so. Meets the requirement for not exactly 10% as well. If you needed more exact results however this would definitely be something better done on the server side.
if(Math.random() * 100 >90){
// greater than 90, so theoretically should only happen 1 out of 10 times do your stuff.
}else{
// Do nothing
}