var text = //string from user input
switch (text) {
case 'yes':
var myint = setInterval(async () => {
//do something
}, 1000);
break;
case 'stop':
clearInterval(myint)
break;
case 'no':
console.log('ok')
break;
default:
console.log('hi');
}
此代码接受用户输入,将其转换为字符串,并将其传递到switch语句如上面的片段所示,当text = 'yes'
时,间隔开始。但当用户输入no(即text = 'no'
(来运行清除间隔时,该间隔不会停止。如何使用或不使用setInterval
?
您必须在case范围之前声明var。
var text = "userinput";
// declare globally
var myint;
switch (text) {
case 'yes':
var myint = setInterval(async () => {
//do something
}, 1000);
break;
case 'stop':
clearInterval(myint)
break;
case 'no':
console.log('ok')
break;
default:
console.log('hi');
}
你是这样说的吗?
var myint;
document.querySelector("select").onchange = function() {
var text = this.value, i = 0;
switch(text) {
case 'yes':
myint = setInterval(async () => {
console.log(++i);
}, 1000);
break;
case 'no':
clearInterval(myint);
break;
}
}
<select>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>