How can I stop the timer permanently based on the user IP address?

Tags: , ,



I want to integrate the below ip based code in my given snippet example. The thing that I want is that the timer got freeze when it is for same ip.

This below code is used to identify the user pc ip.

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

I want to freeze the below timer on the bases of above ip for single single user

$(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>

How can I achieve that by jquery?

Answer

You need to use localStorage to achieve your desired results. localStorage works off each browser.

Firstly, we need to store the IP of user on first page and run the timer first time for user. If the user refreshes the page a message will popup saying that the timer already ran for this IP address.

We are checking the stored IP address with the current IP and if matches we do not run the timer and show OR else we run the timer if the IP is unique.

Live Demo: (You need to use own browser for this demo to work as localStorage does not work in stack snippets.)

$(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>


Source: stackoverflow