2

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

2
  • Beware there are no built-in show|hide methods. Commented Jun 18, 2014 at 8:21
  • we hava a custom java web framework and we are writing javascript in it and we have a method as this.componentID.setVisible(true/false) and I am using it, but thanks anyway. Commented Jun 19, 2014 at 15:04

4 Answers 4

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

setInterval doesn't meant to do it, it call the function again and again in for the given interval.
1

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.

Comments

1

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

Comments

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

This calls the function after the given time is up.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.