How to execute code for X visits

on in Methods, Events and Scopes
Last modified on

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 following JavaScript snippet allows you to set a limit
 * on the number of times a function will execute for any given visitor.
 */

// 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
let limit = 3,
    days = 180;
    cookieName = 'counterCookie';

// Function to fetch cookie values
let getCookie = function (name) {
    let match = document.cookie.match(name+'=([^;]*)');

    return match ? match[1] : undefined;
};

// Function to create cookies
let setCookie = function (c_name, value, exdays, c_domain) {
    c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
    let exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    let 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 {
    let numberPops = parseInt(getCookie(cookieName)) + 1;
    setCookie(cookieName, numberPops, days, window.location.hostname);
}

if (getCookie(cookieName) <= limit) {
    // Function to be evaluated here
}

Related posts