Skip to content
-
JavaScript setTimeout() Method
Last Updated :
28 Apr, 2025
JavaScript setTimeout()
method
allows you to schedule the execution of a function or the evaluation of a code after a specified delay.
The setTimeout()
method calls a function after several milliseconds. setTimeout()
is for executing a function once after a specified delay.
Syntax:
setTimeout(function, delay);
Parameters:
function
: The function or code snippet to be executed after the specified delay.delay
: The time, in milliseconds, to wait before executing the function.
Return Value:
Returns a Number which is the id of the timer. Use this id with clearTimeout(id) to cancel the timer.
Example 1: Here, the greet
function will be executed after a delay of 2000 milliseconds (2 seconds).
JavaScript
function greet() {
console.log("Hello, world!");
}
// Call the greet function after
// 2000 milliseconds (2 seconds)
setTimeout(greet, 2000);
Output: (Will be printed after 2 sec or 2000ms)
Hello, world!
Example 2: Below is the example of popping an up alert, 2 seconds(2000ms) after the user presses the click me button.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport">
<title>Document</title>
</head>
<body>
<button onclick="setTimeout(gfg, 2000);">
Press me
</button>
<script>
function gfg() {
alert('Welcome to GeeksforGeeks');
}
</script>
</body>
</html>
Output:

Note: We can stop the execution of the setTimeout() function by using a method called as clearTimeout() or by closing the window.
Example 3: Here, we are using a setTimeout() function and stop its execution using the clearTimeout() function before the execution of the setTimeout().
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport">
<title>Document</title>
</head>
<body>
<p>Press the stop button
before the alert is shown</p>
<button onclick="val = setTimeout(gfg, 2000);">
Press me
</button>
<button onclick="clearTimeout(val);">
Stop Execution</button>
<script>
function gfg() {
alert('Welcome to GeeksforGeeks');
}
</script>
</body>
</html>
Output:

Similar Reads
JavaScript setInterval() Method The setInterval() method calls a function at specified intervals (in milliseconds). It continues calling the function until clearInterval() is called or the window is closed. This method is useful for tasks that need periodic execution, like updating animations or refreshing data. Important Note: se
2 min read
JavaScript setTimeout() & setInterval() Method JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution.JavaScriptsetTimeout(gf
2 min read
JavaScript setTimeout() & setInterval() Method JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution.JavaScriptsetTimeout(gf
2 min read
JavaScript setTimeout() & setInterval() Method JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution.JavaScriptsetTimeout(gf
2 min read
JavaScript Throttling Throttling is a technique used to limit the number of times a function can be executed in a given time frame. Itâs extremely useful when dealing with performance-heavy operations, such as resizing the window or scrolling events, where repeated triggers can lead to performance issues.JavaScriptfuncti
3 min read
JavaScript Timer A timer has been shown that shows the countdown, and its color/message gets changed after every specific period. Prerequisites: GetMinutes()GetSeconds()SetInterval() MethodSyntax: setTimeout(function, milliseconds, parameter1, ...);Parameter:AttributeDescriptionfunctionIt is the function that will b
2 min read
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}