简体   繁体   English

console.log 给出未定义的变量

[英]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" “未捕获的 ReferenceError:startTime 未定义”

on line:在线的:

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

HTML 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.我认为 startTime 未定义,因为它是 jQuery('#start').click 的局部变量。 Try define startTime upper尝试定义 startTime 上限

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

Ran this on jsfiddle and it worked fine:在 jsfiddle 上运行它,它运行良好:

https://jsfiddle.net/d3eqmbv5/ https://jsfiddle.net/d3eqmbv5/

Just had to remove:只需要删除:

function runTest(){

And I made a fake wordCount function for testing purposes.为了测试目的,我制作了一个假的wordCount函数。

There is a missing parenthesis first if you look at this jsfiddle and tape F12, so what can be the next step ?如果您查看此 jsfiddle 和磁带 F12,则首先缺少括号,那么下一步可以做什么? 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/ https://jsfiddle.net/qugp3fot/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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