简体   繁体   English

防止页面上的setTimeout函数重新加载

[英]prevent setTimeout function on page reload

I am running on Bootstrap 3.3.6. 我在Bootstrap 3.3.6上运行。 I have a very simple setTimeout function that fires a popup window after 10 sec. 我有一个非常简单的setTimeout函数,该函数会在10秒后触发一个弹出窗口。

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. 该代码可以正常工作,并且弹出窗口(#myModal)可以正常打开。

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. 我在这里找到了有关使用localStorage并将其作为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. 但是我对javascript还是很陌生,我很难把它弄对。 Can someone help me out here? 有人可以帮我吗?

Well, I suppose one way to do it might be to create a cookie, and then check for it. 好吧,我想一种方法可能是创建一个cookie,然后检查它。 Perhaps you could create a cookie like this in the script for your home page: 也许您可以在主页的脚本中创建如下所示的Cookie:

 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. 如果我正确地完成了所有操作,那么首先应该检查是否没有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. 如果没有cookie,您的模式警报将关闭,并创建一个名称为“ cookie”和值为“ yes”的cookie。 Since we are not specifying a max age for this cookie, it should expire when the user leaves the site (I think). 由于我们没有为此Cookie指定最长使用期限,因此它应该在用户离开网站时过期(我认为)。 Also, since we set a general path, this cookie should persist across every page. 另外,由于我们设置了通用路径,因此该Cookie应该在每个页面上都保持不变。

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 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM