Skip to content Skip to sidebar Skip to footer

How Can I Show Alert On My Timer When Timer Finished

I am using timer in JavaScript, I want that when my timer is finish it show me alert but right now my timer restart again with same time can any one guide me. how can I show alert

Solution 1:

The issue you are facing is related to count. You set it to 1000. So you will have to wait 1000 min before your function clearInterval(timer) is executed. You can try the following:

Timer restarts after reloading the page

<scripttype="text/javascript">// propertiesvar count = 0;
  var counter = null;

 window.onload = function() {
    initCounter();
  };

 functioninitCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = 6000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

 functiontimer() {
    count = count -1;

   var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;

   if(seconds === 0)
   	{
		clearInterval(counter);
                alert("terminated");
        }
   document.getElementById("timer").innerHTML =  seconds +  "  seconds left to complete this transaction"; // watch for spelling
  }
 </script><divid="timer"></div>

Timer remains unchanged even after restart

<scripttype="text/javascript">// propertiesvar count = 0;
  var counter = null;

 window.onload = function() {
    initCounter();
  };

 functioninitCounter() {
    // get count from localStorage, or set to initial value of 1000if(!count || count < 0)
    {
        count = 1000;
    }
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

 functionsetLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

   return val;
  }

 functiongetLocalStorage(key) {
    returnwindow.localStorage ? window.localStorage.getItem(key) : '';
  }

 functiontimer() {
    count = setLocalStorage('count', count - 1);

   var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;

   if(seconds === 0)
    {
        clearInterval(counter);
        alert("terminated");
        }
   document.getElementById("timer").innerHTML =  seconds +  "  seconds left to complete this transaction"; // watch for spelling
  }
 </script><divid="timer"></div>

It is not a snippet as the first one, because localstorage are disabled in snippet of stackoverflow

Post a Comment for "How Can I Show Alert On My Timer When Timer Finished"