Search code examples
javascript

How to stop live time in Javascript


I want to stop live time in java script. How can I do it. This is my live time javascript source code.

setInterval( function(){
  var d = new Date()
  var h = d.getHours()
  var m = d.getMinutes()
  var s = d.getSeconds()
  h = (h < 10) ? ("0" + h) : h;
  m = (m < 10) ? ("0" + m) : m;
  s = (s < 10) ? ("0" + s) : s;
  document.getElementById("time").value = h +":"+m+":"+s
}, 1000)
  
document.getElementById("time").setAttribute("disabled","disabled")
document.getElementById("time").clearInterval(value)

Solution

  • Use the clearInterval function https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

    The clearInterval() method of the WindowOrWorkerGlobalScope mixin cancels a timed, repeating action which was previously established by a call to setInterval().

    var interval = setInterval(function(){
            var d = new Date()
            var h = d.getHours()
            var m = d.getMinutes()
            var s = d.getSeconds()
            h = (h < 10) ? ("0" + h) : h;
            m = (m < 10) ? ("0" + m) : m;
            s = (s < 10) ? ("0" + s) : s;
            document.getElementById("time").value = h +":"+m+":"+s
    }, 1000)
    
    // this will cancel the interval when you want it to
    clearInterval(interval);