2011-03-15 63 views
0
function count(){ 
    //user input stored in the last index of the array each cycle 
    array[lastindex]=userinput; 
    setInterval(count,5000); 
} 

像我上面的示例代码,我通过存储用户输入来填充数组。但是,我想再添加一个这种情况,即如果用户不在5秒内输入任何内容,我仍然能够存储一个“标记”,表明这一点。换句话说,如何在下一个周期之前自动检测到这一点?谢谢你如何跟踪每个setInterval周期?

+1

没有完全得到你的问题,但clearInterval()可能有帮助 – jimy 2011-03-15 12:33:44

+0

50000不是5秒。 – 2011-03-15 12:34:45

+0

你能解释一下你解决这个问题吗? – Slartibartfast 2011-03-15 13:01:04

回答

0

我想像这样 - 存储一个变量,指示用户现在正在输入。例如,向用户输入的输入添加一个事件,即在空闲5秒后发生变化的变化。

var 
    userTyping = false, 
    typingId; 


$("input").keyup(function(){ 
    userTyping = true; 
    window.clearInterval(typingId); 
    typingId = window.setTimeout(function(){userTyping = false;}, 5000); 
}); 

然后检查:

function count(){ 
//user input stored in the last index of the array each cycle 
if(!userTyping){ 
    array[lastindex]=userinput; 
} 
setTimeout(count,5000); 
} 

请注意,你应该使用的setTimeout即使在函数内部,而不是每次调用时的setInterval - 这将严重结束了......

+0

Thankx男士,这节省了我的生活...欣赏它 – 2011-03-15 21:00:17

0

所以第一个问题是没有新的输入意味着userInputOld === userInputuserInput === ""?我不会猜测,因为比检查它微不足道。

您必须创建一个变量来标记是否有输入。让我们假设键盘输入:

var hasInput = false; 
$("input").keyup(function(){hasInput = true;}) 

然后你就可以在你的代码

function count(){ 
    //user input stored in the last index of the array each cycle 
    if (hasInput) { 
     array[lastindex]=userinput; 
    } else { 
     aray[lastindex]=null; 
    } 
    setInterval(count,5000); 
} 

无论如何,我想问你到底是做什么检查它,因为它看起来像你也许可以做的更好干脆。