如何根据用户IP地址永久停止计时器?

问题描述

我想在给定的片段示例中集成以下基于ip的代码。我想要的是计时器在用于同一IP时冻结。

下面的代码用于标识用户pc ip。

$.getJSON("https://api.ipify.org/?format=json",function(e) {
    console.log(e.ip);
});

我想基于单个IP的ip之上的IP冻结以下计时器

$(function() {
  $('#ms_timer').countdowntimer({
    minutes: 00,seconds: 05,size: "lg",timeUp: () => console.log("Hello")
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://harshen.github.io/jquery-countdownTimer/jquery.countdownTimer.min.js"></script>
<span id="ms_timer" class="d-block mb-2"></span>

如何通过jquery实现这一目标?

解决方法

您需要使用localStorage才能获得所需的结果。 localStorage可在每个浏览器上使用。

首先,我们需要在第一页上存储用户IP并为用户第一次运行计时器。如果用户refreshes到该页面,则会显示一条消息popup,其中说计时器already为此IP地址运行。

我们正在使用IP IP检查存储的current地址,如果匹配,则不运行计时器并显示OR,否则,如果IP为unique,则运行计时器。 / p>

实时演示 :(此演示需要使用自己的浏览器,因为localStorage在堆栈片段中不起作用。)

$(function() {

  let currUserIP
  $.getJSON("https://api.ipify.org/?format=json",function(e) {
    currUserIP = e.ip //set variable
    checkCounter() //check counter
  });

  //get user IP and check if its matches
  function checkCounter() {
    let getUserIp = localStorage.getItem('setUserIP'); //get loca storage
    if (getUserIp != currUserIP) {
      $('#ms_timer').countdowntimer({
        minutes: 00,seconds: 05,size: "lg",timeUp: function() {
          localStorage.setItem('setUserIP',currUserIP);
        }
      });
    } else {
      $('#ms_timer').text('The timer ran already from this IP')
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://harshen.github.io/jquery-countdownTimer/jquery.countdownTimer.min.js"></script>
<span id="ms_timer" class="d-block mb-2"></span>