我如何停止setInterval在案例块中运行

问题描述 投票:0回答:2

            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怎么办?

javascript node.js switch-statement user-input
2个回答
0
投票

您必须在大小写范围之前声明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');
}

0
投票

您的意思是这样吗?

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>
© www.soinside.com 2019 - 2024. All rights reserved.