javascript在执行函数之前等待特定的时间

javascript在执行函数之前等待特定的时间,javascript,Javascript,有没有办法延迟javascript中的函数?我想做这样的事情: function showLabel(){ document.getElementById(id).show(); wait(5000); //wait 5 sec document.getElementById(id).hide(); } 我想显示一个标签5秒钟。如果调用这个函数,可能还有其他方法 注意:我不能使用jQuery提示:使用setTimeout window.setTimeout("javas

有没有办法延迟javascript中的函数?我想做这样的事情:

function showLabel(){
    document.getElementById(id).show();
    wait(5000); //wait 5 sec
    document.getElementById(id).hide();
}
我想显示一个标签5秒钟。如果调用这个函数,可能还有其他方法


注意:我不能使用jQuery

提示:使用
setTimeout

window.setTimeout("javascript function", milliseconds);
阅读文档并了解如何操作:

如果你想睡觉,那么:

function sleep(millis, callback) {
    setTimeout(function()
            { callback(); }
    , milliseconds);
}
我更喜欢:

function doStuff()
{
  //do some things
  setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}

function continueExecution()
{
   //finish doing things after the pause
}
使用循环的另一种方法

<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>

//执行不力
函数睡眠(毫秒){
var startTime=new Date().getTime();//获取当前时间
while(new Date().getTime()
您可以尝试以下方法:

function showLabel(){
    document.getElementById(id).show();
    setTimeout(function()
    {
        document.getElementById(id).hide();
    }, 5000);
}
对一次性任务使用
setTimeout
,对重复性任务使用else
setInterval

setTimeout(
    function(){ Your_function },  milliseconds
);

这将在给定时间结束后调用函数。

在javascript中使用
setTimeout
函数。并在函数调用结束时清除超时

var timerId = setTimeout(function showLabel(){
      document.getElementById(id).show();
        document.getElementById(id).hide();
    }, 5000);
 clearTimeout(timerId);

setInterval并不打算这样做,它会在给定的时间间隔内一次又一次地调用函数。请注意,没有内置的
show | hide
方法。我们有一个自定义java web框架,我们正在其中编写javascript,我们有一个这样的方法。componentID.setVisible(true/false),我正在使用它,不过还是要谢谢。