功能未按正确顺序运行

时间:2020-06-04 15:18:00

标签: javascript

在我的while循环中,我希望

除非我break退出循环,否则它将继续提示用户输入。但是,一旦进入if块,除非我终止代码,否则就不会执行printToScreen(message)函数。

不确定在这里我在做什么错。我希望它在继续提示之前先打印消息。 我该如何解决?

let message;
let search;

function printToScreen(message){
  let outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;  
}

function promptUser (){
    search = prompt("Enter student name");
return search;
}


function searchStudent(){

  while(true){

  search =promptUser();

  for(let i = 0; i<students.length; i++){

    if(search.toLowerCase() === students[i].name.toLowerCase())
    {
      let student = students[i];
      message = `<h4>Student: ${student.name}</h4>`; 
      message += `<p> Track: ${student.track} 
                  <br> Achievements:${student.achievements}
                  <br> Points: ${student.points}
                  </p>`; 
      printToScreen(message);
    }

    else if( search ===null || search.toLowerCase() === 'quit'){
      message = `<p>Thanks.Goodbye! </p>`;

      printToScreen(message);
      break;
    }   
    else{
         message = `<p> Student ${search} does not exist. Try Again!</p>`;
         printToScreen(message);
        }      
     }
  }
}
searchStudent();

1 个答案:

答案 0 :(得分:1)

那是因为浏览器在仍在计算某些js时不会重绘页面。 您可以做的是在setTimeout中用递归调用替换while(true):

function searchStudent(){

  search =promptUser();

  for(let i = 0; i<students.length; i++){

    if(search.toLowerCase() === students[i].name.toLowerCase())
    {
      let student = students[i];
      message = `<h4>Student: ${student.name}</h4>`; 
      message += `<p> Track: ${student.track} 
                  <br> Achievements:${student.achievements}
                  <br> Points: ${student.points}
                  </p>`; 
      printToScreen(message);
    }

    else if( search ===null || search.toLowerCase() === 'quit'){
      message = `<p>Thanks.Goodbye! </p>`;

      printToScreen(message);
      break;
    }   
    else{
         message = `<p> Student ${search} does not exist. Try Again!</p>`;
         printToScreen(message);
    }      
  }

  setTimeout(function(){
      searchStudent();
  },5);
}
searchStudent();