Wednesday 7 September 2016

Javascript Timing Events

In this post, I will explain about JavaScript timing Events. 

The window object allows the execution of code at specified time intervals. These time intervals are called timing events.

The two key methods to use with JavaScript are:

1.    setTimeout(function, milliseconds) - Executes a function, after waiting a specified number of milliseconds.
<!DOCTYPE html>
<html  lang="">
<body>
<button onclick="setTimeout(myFunction, 30000);">Execute after 30 Seconds</button>
<script>
function myFunction() {
    alert('Hello');
}
</script>
</body>
</html>

2.    setInterval(function, milliseconds) - Same as setTimeout(), but repeats the execution of the function continuously.
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock: This page gives alert after every 30 seconds</p>
<script>
function doSomething() {
           var currentdate = new Date();
            var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
            + "/" + currentdate.getFullYear() + " @ "
            + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":" + currentdate.getSeconds();
            if (currentdate.getSeconds() % 30 == 0)
            {
                alert(datetime);
            }
        }
        window.onload = function () {
        setInterval(doSomething, 100);
        }
</script>
</body>

</html>


0 comments:

Post a Comment

Please do not enter any spam link in the message box.