[英]javascript wait specific amount of time before executing a function
is there any way to delay a function in javascript I want to do such thing: 有什么办法可以延迟javascript中的功能吗?
function showLabel(){
document.getElementById(id).show();
wait(5000); //wait 5 sec
document.getElementById(id).hide();
}
I want to show a label for 5 sec if this function is called, there may be another way to do so. 如果要调用此功能,我想显示一个标签5秒钟,可能还有另一种方法。
Note: I can't use jQuery 注意:我不能使用jQuery
Hint: Use setTimeout
提示:使用setTimeout
window.setTimeout("javascript function", milliseconds);
Read the docs and find out how to do it: https://developer.mozilla.org/en/docs/Web/API/window.setTimeout 阅读文档并了解如何执行此操作: https : //developer.mozilla.org/en/docs/Web/API/window.setTimeout
If you want something like sleep then: 如果您想要睡觉之类的东西,请:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, milliseconds);
}
I'd prefer: 我更喜欢:
function doStuff()
{
//do some things
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}
function continueExecution()
{
//finish doing things after the pause
}
Another way using loop 另一种使用循环的方式
<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
You may try this: 您可以尝试以下方法:
function showLabel(){
document.getElementById(id).show();
setTimeout(function()
{
document.getElementById(id).hide();
}, 5000);
}
Use setTimeout
for one time task, else setInterval
for repetitive task. 将setTimeout
用于一次任务,否则将setInterval
用于重复任务。
setTimeout(
function(){ Your_function }, milliseconds
);
This calls the function after the given time is up. 在给定时间结束后,将调用该函数。
use setTimeout
function in javascript. 在javascript中使用setTimeout
函数。 and clear the time out one the function call over 并清除超时功能调用
var timerId = setTimeout(function showLabel(){
document.getElementById(id).show();
document.getElementById(id).hide();
}, 5000);
clearTimeout(timerId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.