0

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

3
  • 3
    Please define "doesnt work". Commented Feb 13, 2017 at 18:08
  • 1
    setTimeout() schedules a function to be invoked once. You may be interested in the related function setInterval(). Commented Feb 13, 2017 at 18:10
  • Thank you everyone Commented Feb 14, 2017 at 7:51

2 Answers 2

2

What you probably want is setInterval instead of setTimeout.

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

Sign up to request clarification or add additional context in comments.

1 Comment

@sanjaybisht Thanks! If you like it, do you mind selecting it as the correct answer and maybe giving it an upvote?
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.