为什么while循环即使在对象引用值发生更改并且应该执行break语句时仍保持循环



在执行命令sw.start()后,当我运行sw.stop()时,它会将值更改为running.value = false,并且应该执行break语句,因为running.value为false,但这并没有发生。。。

这并不完全是一个秒表,而是停止计算程序出错,:(

当我在控制台中运行这个脚本时,会发生一些奇怪的事情:

  • 当我运行sw.stop((时,它可以工作
  • 当我运行sw.restit((时,它起作用
  • sw.duration((也有效
  • 当我运行sw.start((时,它可能会启动计算但在那之后,当运行任何其他命令时,控制台都不会接受任何输入或响应,我必须暂停从源开发工具运行脚本,然后如果我在停止响应后输入了任何命令,它就会显示其他命令的输出。但是在输入sw.start((之后,控制台没有响应
  • 无论如何,有没有什么方法可以让我写另一个方法,以某种方式停止start((方法
  • 换句话说,我可以写一个函数,然后从一个方法调用它来启动它,然后从另一个方法停止它
function StopWatch(){
let current = {t:0};
let running = {value:false};
//this function doesn't stop somehow
const timmy = () => {while(true){
current.t += 0.01;
if(running.value===false){
//this block never runs??
console.log(`stopping...`);
break;
}
};
}
this.start = function(){
if(running.value === true){
throw new Error('It is already running');
} else {
running.value = true;
//timer will go here
timmy();
}
}
//stop doesn't seem to work
this.stop = function(){
if(running.value === false){
throw new Error(`It's is not running.`);
}
else {
running.value = false;
console.log(running.value);
//i hope this works
//
}
}

this.resetit = function(){
if(current.t === 0){
throw new Error(`It's all ready reset`);
}
else{
current.t = 0;
}

}

this.duration = function() {
return `${current.t}s`;
}
}
const sw = new StopWatch();

一些你不必回答的问题:

我可以写一个函数,然后从一个方法调用它来启动它,然后从另一个方法停止它吗。

如何通过调用另一个函数来停止循环的函数,该函数会更改对象或变量的值,如果设置为"false",则会停止循环的功能,因为该函数在对象或变量值上循环,该值是true还是false?甚至有可能??

这导致了问题:

const timmy = () => {
while(true){ // --> never stops
current.t += 0.01;
if(running.value===false){
//this block never runs??
console.log(`stopping...`);
break;
}
};
}

运行时运行循环。value为true:

const timmy = () => { 
while(running.value){
current.t += 0.01;
};
}

While循环总是至少执行一次代码。

因此,当您运行StopWatch((时;对于首次,它将无法正确执行如果你试着运行秒表((;两次它都会起作用。

说到这里,

我们必须使用

如果while循环中存在条件

因此它将检查条件并以正确的方向执行。

最新更新