如何在 javascript 中阻止输入

How to block for input in javascript

从概念上讲,我需要在 javascript 中执行以下操作:

// A) set up stuff

// B) collect values from input
do {
    var key = readKey();
    // do stuff like loading arrays, objects, etc based on this sequential input
} while (key != '.') // period signifies completion

// C) continue to do other stuff that can only be done once the arrays and objects from before are completely loaded.

我知道 javascript 中的 IO 是非阻塞的。所以我尝试设置键盘侦听器并在 setTimeout 构造中循环,但我无法避免程序执行飞到 C) 并出错,因为 B) 的所有先决条件处理均未完成。

这是我尝试过的:

// A) prepare stuff
var digrams = type() // B
// C) deal with digrams (errors out if digrams not complete)

function type() {
  var loopid;

  var loop = function() {
    // NOP
  };

  document.onkeypress = function (e) {
    e = e || window.event;
    var char = String.fromCharCode(e.keyCode);
    ...
    if (char=='.') {
     document.onkeypress = null;
     clearInterval(loopid);
     return digrams; // arr of obj composed thru key input
    }
  } // keylistener

  // Start the type loop
  loopid = setInterval( loop, 10);
}   

我真的需要一种工作方式"against" javascript。任何示例代码将不胜感激。

您可以将 'blocked' 代码放入一个函数中,然后 运行 该函数一旦 keyup 匹配 .

类似于:

function myContinue(){
   ...your blocked code
}

document.onkeypress = function (e) {
... assuming your keypress code is working
    if (char=='.') {
       myContinue();
    }
}

如果要访问 continue 函数外的变量,请在函数外声明它们:

var arrayToLoad;

function myContinue(){
  console.log(arrayToLoad);
}

document.onkeypress = function(e) {
   ...
   arrayToLoad.push(char);
   ...
      myContinue();
   ...
}

或者您可以将 vars 传递给函数

function myContinue(diagrams){
...
}

document.onkeypress = function(e) {
...
  myContinue(diagrams);

您可以使用 Promise,将 return 值异步 .then()

// A) prepare stuff
var digrams = type();
digrams
.then(funcion handleSuccess(value) {
  // do stuff with `value` : `arr` passed to `resolve()`
}
, function handleError(err) {
  // handle error
}); // B
// C) deal with digrams (errors out if digrams not complete)

function type() {
  return new Promise(function(resolve, reject) {
    var loopid;

    var loop = function() {
      // NOP
    };

    document.onkeypress = function (e) {
      e = e || window.event;
      var char = String.fromCharCode(e.keyCode);
      ...
      if (char=='.') {
        document.onkeypress = null;
        clearInterval(loopid);
        resolve(arr);
        // return digrams; // arr of obj composed thru key input
      }
      // reject(new Error("error message"));
    } // keylistener

    // Start the type loop
    loopid = setInterval( loop, 10);
  });
}