Running javascript code only once -
i have piece of js code & want run once. js code contains if statement
if( abc.xyz && xyz.pqr) { //do }
now, abc.xyz & xyz.pqr third party functions being called twice third party code on page & hence jscode have written runs twice. have no control on third party functions. need use them in js code , want code run once. tried using code below not work me:
var donethestuff; if(!donethestuff){ donethestuff= true; //my code // code fires pixel can see in charles // because of third party functions called twice on page // code runs twice & drops 2 pixels instead of 1 can see in charles. }
any suggestions?
you can user underscore.js once() method this.
var dostuff = _.once(function() { if( abc.xyz && xyz.pqr) { //do } });
and if want know how works, can browse source yourself:
http://underscorejs.org/docs/underscore.html#section-73
_.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; };
Comments
Post a Comment