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'
时,间隔开始。但是,当用户未输入任何时间(即text = 'no'
)来运行清除间隔时,该间隔不会停止。有或没有setInterval
怎么办?
您必须在大小写范围之前声明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>