Run JavaScript code or call a function after n seconds

In this short tutorial, we are going to show you how to run our JavaScript code or call a function after a specific time or after n seconds after the window load.

Suppose we want to alert a message after n seconds of window load in JavaScript. Well, we can do it easily using JavaScript. JavaScript has a method which is setTimeout() method that we are going to use to delay in running our JavaScript code or delay in the function call. We can use this method to call our function after a specified time or run our JavaScript code.

Delay in running the JS code

Below is an example that will alert a message after 7 seconds:

setTimeout(function(){ 
   alert("This alert appears after 7 seconds");
}, 7000);  // Set the time out to 7 seconds

If we run the above JavaScript code then we will see the alert message appear after 7 seconds.

Run your JavaScript code every n seconds using setInterval() method

Validating phone numbers in JavaScript

Below is another example where we are calling a function inside setTimeout method:

setTimeout(delayLoad, 4000);
function delayLoad() {
  alert("This alert message appear after 4 seconds");
}

In the above code, we have created a JavaScript function and then called it through setTimeOut method. If we run the code, then it will show the alert message after 4 seconds of window load. Here we have called a function after for seconds.

Call a function after clicking a button with a delay

You can delay running the code in the button onclick event. To achieve this, you have to use the setTimeout method inside the onclick event. Below is showing an example of this task:

<button id="myBtn">Click me</button>


<script type="text/javascript">
document.getElementById("myBtn").onclick = function() {
   callme();
};

function callme() {
    setTimeout(function(){
       alert("This alert appears with 7 seconds delay after you click the button");
     }, 7000); // Set the time out to 7 seconds
}

</script>

 

In the above code, we first create our HTML button using the button tag and assign the ID myBtn. Inside the onclick event we are calling our function that contains the code delaying execution of our JavaScript code for 7 seconds. Now when we click our button, the button is going to show the alert message after 7 seconds of click event.

Leave a Reply

Your email address will not be published. Required fields are marked *