如何在我的javascript中延迟执行以下操作 [英] How to delay execution in between the following in my javascript
问题描述
我想在下面的代码中延迟执行:
I want to delay execution in betwen the follwoing codes:
$("#myName").val("Tom");
///delay by 3s
$("#YourName").val("Jerry");
//delay by 3s
$("#hisName").val("Kids");
推荐答案
您可以使用 setTimeout
:
You can use setTimeout
for that:
setTimeout(function() {
// Your code here
}, delayInMilliseconds);
例如:
$("#myName").val("Tom");
/// wait 3 seconds
setTimeout(function() {
$("#YourName").val("Jerry");
/// wait 3 seconds
setTimeout(function() {
$("#hisName").val("Kids");
}, 3000);
}, 3000);
setTimeout
安排要运行的功能(一段时间后。调用它的代码会继续,并且在将来的某个时刻(在大致指定的时间之后,虽然不精确),该函数会被浏览器调用。
setTimeout
schedules a function to be run (once) after an interval. The code calling it continues, and at some point in the future (after roughly the time you specify, though not precisely) the function is called by the browser.
所以假设你有一个名为 output
的函数,它将文本附加到页面。输出:
So suppose you had a function called output
that appended text to the page. The output of this:
foo();
function foo() {
var counter = 0;
output("A: " + counter);
++counter;
setTimeout(function() {
output("B: " + counter);
++counter;
setTimeout(function() {
output("C: " + counter);
++counter;
}, 1000);
}, 1000);
output("D: " + counter);
++counter;
}
...是(几秒钟后):
...is (after a couple of seconds):
A: 0
D: 1
B: 2
C: 3
注意第二行。其余的 foo
的代码在任一计划函数之前运行,因此我们在之前看到 D
行。 B
line。
Note the second line of that. The rest of foo
's code runs before either of the scheduled functions, and so we see the D
line before the B
line.
setTimeout
返回一个句柄(是一个非零数字)你可以用它来取消回调:
setTimeout
returns a handle (which is a non-zero number) you could use to cancel the callback before it happens:
var handle = setTimeout(myFunction, 5000);
// Do this before it runs, and it'll never run
clearTimeout(handle);
还有相关的 setInterval
/ clearInterval
它做同样的事情,但是在你指定的间隔重复(直到你停止它)。
There's also the related setInterval
/ clearInterval
which does the same thing, but repeatedly at the interval you specify (until you stop it).
这篇关于如何在我的javascript中延迟执行以下操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!