简体   繁体   中英

console.log gives undefined on a variable

I have a timer function (it calculates how many words were read in given time but my code doesn't work).

It says:

"Uncaught ReferenceError: startTime is not defined"

on line:

"testTime = (stopTime - startTime)/1000 + testTime;" 

HTML

<button class="btn" id="start">Start Reading</button>
  <div id="page1" style="display: block;"><p class="title">
    Text goes here
 </div>
  <button class="btn" id="stop">Finished!</button>
  <span id="wordValue"></span>
  <span id="timeValue"></span>

JAVASCRIPT

function runTest(){

 testRunning = false;
 restart = false;
 var testTime = 0;

 jQuery('#start').click(function(){
   startTime = new Date().getTime();
   testRunning = true;
 });

  jQuery('#stop').click(function(){

    stopTime = new Date().getTime();
    testTime = (stopTime - startTime)/1000 + testTime;


    testRunning = false;
    // set wpm =  calculated words per minute
    wpm = Math.round(wordCount('#page1') / (testTime / 60));
    // set difference = calculated difference between words per minute and     national average (250)
    difference = Math.round(100*((wpm/250)-1));
    if (difference < 0) {
      difference = difference*-1 + '% slower';
    } else {
      difference = difference+'% faster';
    }
  });

I think startTime is not defined because it's a local variable to jQuery('#start').click. Try define startTime upper

var testRunning = false;
var restart = false;
var testTime = 0;
var startTime = 0; // here

Ran this on jsfiddle and it worked fine:

https://jsfiddle.net/d3eqmbv5/

Just had to remove:

function runTest(){

And I made a fake wordCount function for testing purposes.

There is a missing parenthesis first if you look at this jsfiddle and tape F12, so what can be the next step ? to shutt the function right after or at the end of the complete block of code ?

function runTest(){
    testRunning = false;
    restart = false;
    var testTime = 0;

https://jsfiddle.net/qugp3fot/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM