2013-02-19 2 views
0

사용자가 특정 시간 내에 특정 문자 집합을 입력했는지 확인하려고합니다.특정 시간 내에 특정 문자를 입력했는지 감지합니다.

나는 뭔가를 만들었다 고 생각 하긴하지만 전역 변수 toMatch를 사용하기 때문에 좋지 않다는 것을 알고 있습니다. var 키워드없이 setInterval로 선언했습니다. 범위에 대한 아이디어가 저를 혼란스럽게 만들었지 만 배우려고 노력하고 있으며 누군가가 더 나은 방법을 제공 할 수 있는지 궁금합니다. 현실에서 당신은 단지 사용자가 가지고 있는지 확인해야하기 때문에 -

jsbin

//set the toMatch array equal to the character codes for the word 'test' 
//reset it to its original value every 2seconds 
var matchTime = setInterval(function(){ console.log('toMatch reset'); toMatch = [84,69, 83, 84];}, 2000); 


document.addEventListener("keydown", function(e){ 

    var key = e.which; 
    findMatches(key); 

}); 

function findMatches(key){ 

    //if the key is in the first position in the array, remove it 
    if (key == toMatch[0]){ 
     toMatch.shift(); 

    } 
     console.log(toMatch); 

    //if all shifted out, clear the interval 
    if (toMatch.length == 0) { 
    window.clearInterval(matchTime); 
    alert('typed \'test\' within two seconds'); 
    } 

} 

+0

왜 'findMatches'에서 정의 할 수 없습니까? –

+0

@Nicholas array.shift()를 사용하면 어떻게됩니까? – luckystars

답변

0

내 코드는 setInterval 호출이없는이

function listenForWord(word) { 
    word = word.toUpperCase(); // event char codes are in upper case 
    var counter = 0, 
     time = 0; 
    // I used jQuery, you could also use addEventListener but don't 
    // forget to use attachEvent so it works in all browsers! 
    $(document).keydown(function (e) { 
     // Because the code is inside a function, the variable 
     // word is available at this level but is not global 
     var currentTime = new Date().getTime(); 
     if (currentTime - time > 1000) { 
      // If the user waits more than 1 second to type the next letter 
      // The counter is reset, I'm not sure if this is what you want! 
      counter = 0; 
     } 
     var character = word.charCodeAt(counter), 
      first = word.charCodeAt(0); 
     if (character == e.which) { 
      counter++; 
     } else if (character == first) { 
      counter = 1; 
     } else { 
      counter = 0; 
     } 
     if (counter == word.length) { 
      counter = 0; 
      alert("You typed " + word + " fast enough"); 
     } 
     time = currentTime; 
    }); 
} 

listenForWord("test"); 
// You could potentially call this function with other words 
// And it will work 

참고하십시오 감사 그가 실제로 키를 누를 때 올바른 단어를 입력 할 수 있습니다. 간격을두고 어떤 종류의 재설정도 수행 할 필요가 없습니다.

사용자가 최대 4 초 동안 입력 할 수 있으므로 입력 한 각 키 사이에 1 초 이상을 입력 할 수 없으므로 정확히 일치하지 않습니다.

2 초 제한 시간 내에 모든 4자를 입력했는지 테스트하려면 첫 번째 키를 누를 때 저장된 시간을 대신 논리를 다시 구성 할 수 있습니다. 그런 다음 현재 시간과 그 시간을 비교하십시오 마지막 키 누름 시간보다

+0

다음은 실시간 데모입니다. http://jsfiddle.net/kagsM/ – codefactor

0

전역 변수를 피하는 것이 주된 문제라면 간단한 대답은 즉시 호출 된 함수 식 (IIFE)을 살펴 보는 것입니다. Ben Alman은 여기 좋은 기사를 가지고 있습니다 : http://benalman.com/news/2010/11/immediately-invoked-function-expression/

기본적으로 모든 변수/기능을 자체 범위에 캡슐화하고 바로 호출합니다. 최소한의 변경만으로 코드에 적용 할 수 있습니다.

 

//Begin IIFE 
(function(){ 
    //declare toMatch variable inside IIFE scope - prevents it from polluting the global scope 
    var toMatch; 
    //set the toMatch array equal to the character codes for the word 'test' 
    //reset it to its original value every 2seconds 
    var matchTime = setInterval(function(){ 
     console.log('toMatch reset'); 
     toMatch = [84,69, 83, 84]; 
    }, 2000); 

    document.addEventListener("keydown", function(e){ 
     var key = e.which; 
     findMatches(key); 
    }); 

    function findMatches(key){ 

     //if the key is in the first position in the array, remove it 
     if (key == toMatch[0]){ 
      toMatch.shift(); 
     } 
     console.log(toMatch); 

     //if all shifted out, clear the interval 
     if (toMatch.length == 0) { 
      window.clearInterval(matchTime); 
      alert('typed \'test\' within two seconds'); 
     } 

    }; 
})(); 


console.log(window.toMatch) // now toMatch isn't a global variable 

+0

감사합니다. Ryan. 내 주요 목표는 글로벌 변수를 피하는 것이 아니라고 생각합니다. 나는 단지 그것들이 아마 더 큰 문제가되는 징후라고 인식 할 수 있습니다. 처음에는 즉각적인 함수로 시도했지만,'toMatch'는 정의되지 않았습니다 ... 몇 초 동안 오류가 발생했습니다 ... 그러면 작동하는 것처럼 보였습니다. 이상한.. – 1252748

관련 문제