This JavaScript will let you execute code a certain number of times. For example, you might want to only show a pop up to visitors on their first 3 visits.
// the number of times the code should execute for a given visitor, // the number of days the evaluation limit should last, // and name of the cookie we use as the counter var limit = 3, days = 180; cookieName = 'counterCookie'; // function to fetch cookie values var getCookie = function(name) { var match = document.cookie.match(name+'=([^;]*)'); return match ? match[1] : undefined; }; // function to create cookies var setCookie = function(c_name,value,exdays,c_domain) { c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";"; var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/"; } // logic that counts and limits number of times code can evaluate for given visitor if (!getCookie(cookieName)) { setCookie(cookieName, 1, days, window.location.hostname); } else { var numberPops = parseInt(getCookie(cookieName)) + 1; setCookie(cookieName, numberPops, days, window.location.hostname); } if (getCookie(cookieName) <= limit) { // Function to be evaluated here }
This code was shamelessly stolen from getbutterfly.com – check them out for lots more Javascript tutorials!