Wil Carter
Wil Carter

Reputation: 63

prevent setTimeout function on page reload

I am running on Bootstrap 3.3.6. I have a very simple setTimeout function that fires a popup window after 10 sec.

setTimeout(function(){
        $('#myModal').modal('show');
        }, 10000);

I added this script at the end of my homepage. This code works perfectly and the popup (#myModal) opens up just fine.

Problem is, if I visit another page on my site and then hit the back button, or click home on the navbar, the pop up fires again.

I found an answer on here about using localStorage and running it as an if/else. Basically make it so that you will only see the popup the first time you visit that page. But I am very new to javascript and I am having a hard time getting it right. Can someone help me out here?

Upvotes: 1

Views: 688

Answers (2)

Jordan Carter
Jordan Carter

Reputation: 1336

Well, I suppose one way to do it might be to create a cookie, and then check for it. Perhaps you could create a cookie like this in the script for your home page:

window.onload = function() {
  
  
  if (!document.cookie){
        setTimeout(function(){
            $('#myModal').modal('show');
            }, 10000);
        document.cookie = "cookie=yes; path=/";
    }
  

}

If I've done everything properly, what this should do first is check to see if there isn't a cookie. If there isn't a cookie, your modal alert goes off and a cookie with a name of "cookie" and a value of "yes" gets created. Since we are not specifying a max age for this cookie, it should expire when the user leaves the site (I think). Also, since we set a general path, this cookie should persist across every page.

Upvotes: 2

blurfus
blurfus

Reputation: 14031

I would use a simple approach like this:

// load flag from localStorage
var alreadyDisplayed = localStorage.getItem('alreadyDisplayed');

// if not found or found but 'false' - display modal (alert in this case)
if (!alreadyDisplayed || alreadyDisplayed == 'false') {

  setTimeout(function() {
    alert('show');
    // store to localStorage the fact that we displayed the modal
    localStorage.setItem('alreadyDisplayed', 'true');
    
  }, 5 * 1000); // in ms, so 5*1000 = 5 secs
}

Upvotes: 0

Related Questions