Menu ▼



Posted By :
avatarmrkraju
Total Views : 352

JavaScript setTimeout function example.

When we want to perform a particular action or call a particular javascript method after a specific time, then we can achieve it by using javascript inbuilt function setTimeout.

"setTimeout" function will take 2 parameter , the first one is function and the second parameter is time in milliseconds.

Syntax : setTimeout(function, timeout);
where the function can be write there it self, are can write separately and can pass the function name as parameter.

Example

alert me after seconds

Method 1 : Writing javasript method as a parmeter

function showalert() {
    var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
    setTimeout(function () { alert(new Date()); }, timedelay);
}

Method 2 : Writing javasript method separately and passing method name as a parmeter

function showalert() {
    var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
    setTimeout(showtime, timedelay);
}
function showtime() {
    alert(new Date());
}

Source Code

<html>
<head>
    <title></title>
    <script language="javascript">
        function showalert() {
            var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
            setTimeout(function () { alert(new Date()); }, timedelay);
        }
        function showtime() {
            alert(new Date());
        }
    </script>
</head>
<body>
    alert me after
    <input type="text" id="txttimerdelay" value="2" style="width: 40px; text-align: center;" />
    seconds<input type="button" value="Show Alert" onclick="showalert();" />
</body>
</html>





comments powered by Disqus


Search dotnetlearners.com