javascript settimeout cleartimeout 例程语法
这是来自另一个线程的代码。仅当用户在设定时间后停止打字时,它才会激活功能。
var keyupTimer;
function keyUpEvent(){
clearTimeout(keyupTimer);
keyupTimer = setTimeout(sendInput,1000); // will activate when the user has stopped typing for 1 second
}
function sendInput(){
alert("Do AJAX request");
}
它按原样工作。但是,如果我在这一行中添加括号来尝试传递变量,为什么它会停止工作:
keyupTimer = setTimeout(sendInput,1000); //original code
To
keyupTimer = setTimeout(sendInput(),1000); //with just empty ()
或
keyupTimer = setTimeout(sendInput(var),1000);//or with ('test') or with (var)
with the括号,不会发生延迟并且立即调用 sendInput 函数。这是该特定例程的唯一格式吗?
TIA
This is the code from another thread. It activates a function only when the user has stopped typing after a set time.
var keyupTimer;
function keyUpEvent(){
clearTimeout(keyupTimer);
keyupTimer = setTimeout(sendInput,1000); // will activate when the user has stopped typing for 1 second
}
function sendInput(){
alert("Do AJAX request");
}
It works as is. But why does it stop working if I put parenthesis to try to pass variables in this line:
keyupTimer = setTimeout(sendInput,1000); //original code
To
keyupTimer = setTimeout(sendInput(),1000); //with just empty ()
or
keyupTimer = setTimeout(sendInput(var),1000);//or with ('test') or with (var)
with the parenthesis, the delay does not occur and the sendInput function is called immediately. Is this the only format for this particular routine?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这表示“1000ms后运行sendInput”;
这表示“运行sendInput,捕获返回值(应该是一个函数)并在1000ms后运行它”。
sendInput
是一个函数,sendInput()
是一个函数call。This says "Run sendInput after 1000ms";
This says "Run sendInput, capture the return value (which should be a function) and run that after 1000ms".
sendInput
is a function,sendInput()
is a function call.setTimeout
的第一个参数是函数引用(即指向函数的变量)。您提供的是一个函数调用。要传递带有参数的函数,请将函数调用包装在匿名函数中。您可以将其作为参数直接传递给setTimeout
,因为 JavaScript 函数是一等对象。更详细地说,这等于:
内联模式的优点是它可以访问调用 setTimeout 的范围。
如果它更适合您,您甚至可以创建一个回调工厂来将函数调用传递给
setTimeout
作为 @斯莱贝特曼指出。The first argument for
setTimeout
is a function reference (i.e. a variable that points to your function). What you provided is a function call. To pass a function with arguments, wrap the function call in an anonymous function. You can pass it directly tosetTimeout
as an argument since JavaScript functions are first-class objects.In more verbose, that equals to this:
The inline pattern has its advantage that it has access to the scope where the
setTimeout
is called.If it fits better to you, you could even create a callback factory to pass a function call to
setTimeout
as @slebetman pointed out.您可以尝试
使用匿名函数作为“setTimeout”的参数
you can try
so have an anonymous function as parameter for 'setTimeout'
也可以使用包含 javascript 代码的字符串作为
setTimeout
的第一个参数。然而,强烈建议不要这么做(见评论)it is also possible to use a string containing javascript code, as a first argument to
setTimeout
. however, it is strongly discouraged (see comments)