Aadi
Aadi

Reputation: 7109

Wait before firing a function to execute in JavaScript

How can I set a delayed trigger in JavaScript to execute a function after a specified amount of time?

My program will wait for 5 seconds to execute demo(); and if it fails to start demo within 5 seconds I need to execute sample() automatically.

Is this possible to do in JavaScript?

Upvotes: 11

Views: 21854

Answers (4)

Jobst
Jobst

Reputation: 559

<script language="javascript">
function sample() {
  alert('sample here');
}
function demo() {
  alert('demo here');
}
setTimeout("sample()", 5000);
</script>

<input type=button onclick="demo();">

Upvotes: 2

GlenCrawford
GlenCrawford

Reputation: 3389

You can invoke functions after a period of time with setTimeout

setTimeout(demo, 5000);

I'm not sure that I get the "if it is fail to start demo with in 5 seconds" part of your question, because the above code will execute demo() in 5 seconds.

Upvotes: 12

Sarfraz
Sarfraz

Reputation: 382686

Have a look at:

Example:

setTimeout(function(){your code here}, 3000)

Upvotes: 7

rahul
rahul

Reputation: 187030

You can use setTimeout for a pause in javascript.

setTimeout(function(){callSample();}, 5000);

then set a global variable inside demo() so that you can identify whether demo() has been called or not and then in

function callSample()
{
    if (variable set)
    {
        sample();
    }
}

Upvotes: 1

Related Questions