bdogru
bdogru

Reputation: 842

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:

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.

Note: I can't use jQuery

Upvotes: 2

Views: 2907

Answers (4)

Chankey Pathak
Chankey Pathak

Reputation: 21676

Hint: Use 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

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>

Upvotes: 1

Vignesh
Vignesh

Reputation: 1063

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

This calls the function after the given time is up.

Upvotes: 0

chandu
chandu

Reputation: 2276

use setTimeout function in javascript. 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);

Upvotes: 1

user2575725
user2575725

Reputation:

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.

Upvotes: 1

Related Questions