Sometimes, you may want to execute Javascript code after a specific time. This is useful when you want to wait for specific event complete before code executes. For example, you want to send request after 1 second of user stop typing. This is required to send request to server only after user complete to typing keywords instead of sending request on every character.
In this example, we will discuss on how you can execute Javascript code after certain time. We will also discuss how you can prevent to run code which were set on setTimeout method.
The setTimeout method executes specified function or piece of code after specific given time.
setTimeout(function, milliseconds, arg1, arg2, ...)
function
which executes after timer expires.
milliseconds
optinal is time expires it
arg1, arg2
optional parameters pass in the function.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setTimeout method</title>
</head>
<body>
<script type="text/javascript">
setTimeout(function() {
alert('Hello World!');
}, 2000);
</script>
</body>
</html>
clearTimeout
method cancels the code to be execute set in setTimeout method.
clearTimeout(setTimeoutVariable)
setTimeoutVariable
is the variable defined for setTimeout method.This is useful to stop executing code set in setTimeout method. For example, stop to send request server when user start typing before request was send.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>clearTimeout method</title>
</head>
<body>
<button onclick="createAlert()">Alert</button>
<button onclick="stopAlert()">Stop Alert</button>
<script type="text/javascript">
var newAlert;
function createAlert() {
newAlert = setTimeout(function() {
alert('Hello World!.');
}, 5000);
}
function stopAlert() {
clearTimeout(newAlert);
}
</script>
</body>
</html>
So far in this article, we have learn how to execute Javascript code after a specific time. We have also learned to prevent executing code set in setTimeout method. I hope you liked the article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to configure NFS on Linux
NFS or Network File System is used to sh...Image Crop and Upload using Croppie jQuery plugin
In every social networking website, ther...[previous exception] [object] (PDOException(code: 0): could not find driver
In this article, i will share with you h...Python Numpy Array Tutorial Part 2
In the first part, we have discussed wha...PDF viewer integration with Example in Angular
If you require to visually perceive an e...