最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - 1-Min Countdown Javascript - Stack Overflow

programmeradmin5浏览0评论

I'm attempting to build a typing test that begins counting down when the user presses a key in the text area. I thought an if-else loop would help display and start the 1-minute countdown timer in my HTML but that's not the case.

Please explain to me what I'm doing wrong & how to correct my code.

HTML:

<div id="timer"></div>
<p>Text for typing test will go here.</p>
<textarea id="textarea" rows="14" cols="150" placeholder="Start typing here...">
</textarea>`

JS:

var seconds=1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;
var textarea = document.getElementById("textarea").onkeypress = function() { 
    myFunction()
};
//When a key is pressed in the text area, update the timer using myFunction

function myFunction() {
   document.getElementById("timer").innerHTML = 
     if (seconds>=0) {
         seconds = seconds--;
     } else {
         clearInterval("timer");
         alert("You type X WPM");
     }
} //If seconds are equal or greater than 0, countdown until 1 minute has passed
//Else, clear the timer and alert user of how many words they type per minute

document.getElementById("timer").innerHTML="0:" + seconds; 

I'm attempting to build a typing test that begins counting down when the user presses a key in the text area. I thought an if-else loop would help display and start the 1-minute countdown timer in my HTML but that's not the case.

Please explain to me what I'm doing wrong & how to correct my code.

HTML:

<div id="timer"></div>
<p>Text for typing test will go here.</p>
<textarea id="textarea" rows="14" cols="150" placeholder="Start typing here...">
</textarea>`

JS:

var seconds=1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;
var textarea = document.getElementById("textarea").onkeypress = function() { 
    myFunction()
};
//When a key is pressed in the text area, update the timer using myFunction

function myFunction() {
   document.getElementById("timer").innerHTML = 
     if (seconds>=0) {
         seconds = seconds--;
     } else {
         clearInterval("timer");
         alert("You type X WPM");
     }
} //If seconds are equal or greater than 0, countdown until 1 minute has passed
//Else, clear the timer and alert user of how many words they type per minute

document.getElementById("timer").innerHTML="0:" + seconds; 
Share Improve this question edited Feb 9, 2016 at 18:28 rrk 15.8k4 gold badges30 silver badges47 bronze badges asked Feb 9, 2016 at 18:23 Rasheeda AlexanderRasheeda Alexander 451 gold badge1 silver badge5 bronze badges 6
  • 2 you're calling clearInterval, but where do you setInterval? this will help: developer.mozilla/en-US/docs/Web/API/WindowTimers/… – manonthemat Commented Feb 9, 2016 at 18:26
  • 1 your min is equal to 1 hour not 1 min. – Adam Buchanan Smith Commented Feb 9, 2016 at 18:27
  • document.getElementById("timer").innerHTML = is invalid syntax; didn't you want to finish this line? What do you want to assign? – Chiru Commented Feb 9, 2016 at 18:30
  • there are syntax errors all over the place. – Adam Buchanan Smith Commented Feb 9, 2016 at 18:36
  • @manonthemat I'm assuming that my setInterval should read as follows: var aVar = setInterval (function() { myFunction()}, 1000); – Rasheeda Alexander Commented Feb 9, 2016 at 18:49
 |  Show 1 more ment

5 Answers 5

Reset to default 5

There are some problems with your solution that I noticed.

1) You clearInterval, but you never setInterval

2) seconds = seconds--, does not do what you think it does because of order of operations in JavaScript.

I modified your JS and have a working solution in this codepen

JS:

var seconds=60;
var timer;
function myFunction() {
  if(seconds < 60) { // I want it to say 1:00, not 60
    document.getElementById("timer").innerHTML = seconds;
  }
  if (seconds >0 ) { // so it doesn't go to -1
     seconds--;
  } else {
     clearInterval(timer);
     alert("You type X WPM");
  }
}
document.getElementById("textarea").onkeypress = function() {
  if(!timer) {
    timer = window.setInterval(function() { 
      myFunction();
    }, 1000); // every second
  }
} 

document.getElementById("timer").innerHTML="1:00"; 

There were lots syntax errors in your code. You need to use setInterval function to start the continuous call of your function. More importantly,

var seconds = 1000 * 60; //1000 = 1 second in JS
var min = seconds * 60;

These calculations were another problem.

1000 * 60 means 60 seconds, so seconds * 60 gives you 60 minutes.

Like one of the ments said, there are syntax errors all over the place.. You need to get more insight into coding using JavaScript.

var seconds = 1000 * 60; //1000 = 1 second in JS
var textarea = document.getElementById("textarea");
var timer;
textarea.addEventListener("keypress", myFunction)
//When a key is pressed in the text area, update the timer using myFunction

function myFunction() {
   textarea.removeEventListener("keypress", myFunction);
   if(seconds == 60000)
     timer = setInterval(myFunction, 1000)
   seconds -= 1000;
   document.getElementById("timer").innerHTML = '0:' + seconds/1000;
   if (seconds <= 0) {
       clearInterval(timer);
       alert("You type X WPM");
   }
} //If seconds are equal or greater than 0, countdown until 1 minute has passed
//Else, clear the timer and alert user of how many words they type per minute

document.getElementById("timer").innerHTML= "0:" + seconds/1000;
<div id="timer"></div>
<p>Text for typing test will go here.</p>
<textarea id="textarea" rows="14" cols="150" placeholder="Start typing here...">
</textarea>

I rewrite your code, i think that it ill attempt your needs:

Javascript:

var seconds = 0, stop = 60, counterStarted = false, counter;
function myFunction(){
if(counterStarted === false){
counterStarted = true;
counter = setInterval(function(){
    if(seconds <= stop){
    document.getElementById('timer').innerHTML = seconds;
    seconds++;
  }else{
 document.getElementById('textarea').setAttribute("disabled", "disabled");
        clearInterval(counter);
        counterStarted = false;
        seconds = 0;
      }
    },1000)
  }
}

HTML:

<div id="timer"></div>
  <p>
Text for typing test will go here.  </p>
<textarea id="textarea" rows="14" cols="150" placeholder="Start typing here..." onkeypress="myFunction()"></textarea>

JsFiddle Example

I've put together a small solution for you:

JavaScript:

    var textarea = document.getElementById("textarea").onkeypress = function(){
        myFunction()
    }
    var totalTime = 10
    var currentTime = totalTime
    var firstTap = true
    var timer = null

    function myFunction() {
        if (firstTap == true){
            firstTap = false
            timer = setInterval(function(){
                currentTime--
                document.getElementById("timer").innerHTML = currentTime;
                if (currentTime < 0){
                    currentTime = totalTime
                    document.getElementById("timer").innerHTML = currentTime;
                    clearInterval(timer);
                    alert("You type X WPM");
                    firstTap = true
                }
            }, 1000)
        }
    }

    document.getElementById("timer").innerHTML = currentTime

The main thing I changed, was that you need to store your timer, and have the callback of your interval be updating your timer display, not the myFunction(). Think about it, as you had the code your "timer" div would only update when you typed. You want that to update no matter what the user is doing if its a timer.

I put some basic gating logic to detect whether its your first keystroke so you don't start the timer 1000 times, and I just reset it when the alert appears. I also stored the total time at the top and you can set it to whatever value you want. I tested with 10 seconds since I didn't want to wait a minute, but you can move it to whatever you want.

I did this a pletely different way since there were so many syntax errors and would not work correctly anyways, see fiddle: https://jsfiddle/rtza7nm0/

  var counter = 0;

  function startTimer(duration, display) {
    var timer = duration,
      minutes, seconds;
    setInterval(function() {
      minutes = parseInt(timer / 60, 10)
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.textContent = minutes + ":" + seconds;

      if (--timer < 0) {
        alert("You type " + counter + " WPM");
        timer = duration;
      }
    }, 1000);
  }

  function myFunction() {
    if (counter == 0) {
      var oneMinute = 60,
        display = document.querySelector('#timer');
      startTimer(oneMinute, display);
      counter++;
    } else {
      counter++;
    }
  };
发布评论

评论列表(0)

  1. 暂无评论