sanjay bisht
sanjay bisht

Reputation: 47

Timer in javaScript doesnt work

I am making a simple timer in javaScript which starts when you click anywhere in the document and it resets on clicking again.

var k = 0,
  m = 0,
  s = 0;
document.onclick =
  function() {
    k = 0;
    setTimeout(function() {
      k++;

      if (Math.floor(k / 6000) > 1) {
        m = Math.floor(k / 6000);
        s = Math.floor(k % 6000);
      } else
        s = Math.floor(k / 100);
      document.getElementById('input3').value = "0" + m + ":" + "0" + s + "  " + k;
    }, 10);
  };

input3 is the id of textbox in html in timer in which countdown is displayed

Upvotes: 0

Views: 80

Answers (2)

joe_coolish
joe_coolish

Reputation: 7259

What you probably want is setInterval instead of setTimeout.

I made this example that sounds like what you want. https://jsfiddle.net/5yke1hmp/

Upvotes: 2

Mohd Asim Suhail
Mohd Asim Suhail

Reputation: 2292

setTimeout(function() { is the problem, if you want to create a timer you should use setInterval(function() {

setInterval will execute the function after every ''specified time' while setTimeout will only run the function once after 'specified time'

Upvotes: 1

Related Questions