Run javascript function once a week

眉间皱痕 提交于 2021-02-08 09:34:13

问题


I have the below javascript function that currently runs on every visit. I do not want to spam our visitors with this popup on every visit so I am trying to get my head around cookies and running this once a week.

setTimeout(function() {
    jQuery(document).one('mouseleave', function() {
        console.log('mouse left');
        jQuery('.open-popup-link').magnificPopup('open');
    });
}, 10000);

I placed this within a cookie function that I found on here however nothing runs and no errors in the console.

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
}   
function checkCookie() {
    var pinball = getCookie("pinball");
    if (pinball === "") { // Cookie not set
        setTimeout(function() {
            jQuery(document).one('mouseleave', function() {
                console.log('mouse left');
                jQuery('.open-popup-link').magnificPopup('open');
            });
        }, 10000);
        setCookie("pinball", "seen", 7);
    }
}

What have I missed or need to do to make this run?


回答1:


I agree with @MysterX about local storage, but to answer your question - from reading your code - there does not seem to be a call to trigger checkCookie() which means that there are no errors because the function has not run.

You should probably have:

$(document).ready(function(){
checkCookie()
})

also you have a typo in the first section of code and in the checkCookie function as well - same error - you have :

 jQuery(document).one('mouseleave', function() {...

and it should be .

 jQuery(document).on('mouseleave', function() {...



回答2:


Using localStorage, only call checkSeen once per page load, or execute it inside of setInterval for browsers that never close.

function popup() {
  ...
}

function updateSeen() {
  var sec = Math.round(Date.now()/1000);
  localStorage.setItem("seen", sec);
  return sec;
}

function checkSeen() {
  var seen = localStorage.getItem("seen") || updateSeen();
  var now = Math.round(Date.now()/1000);
  var week = 604800;
  if ((now - seen) >= week) {
    updateSeen();
    popup();
  }
}

checkSeen();


来源:https://stackoverflow.com/questions/36056755/run-javascript-function-once-a-week

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