JavaScript Timing Events PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a tutorial on JavaScript timing events, focusing on setTimeout and clearTimeout methods. It explains how to execute code after a specified time interval and also covers creating timers in infinite loops.
Full Transcript
JavaScript Timing Events With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events. It's very easy to time events in JavaScript. The two key methods that are used are: setTimeout() - executes a code some time in the future clearTimeout() -...
JavaScript Timing Events With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events. It's very easy to time events in JavaScript. The two key methods that are used are: setTimeout() - executes a code some time in the future clearTimeout() - cancels the setTimeout() The setTimeout() Method Syntax var t=setTimeout("javascript statement",milliseconds); The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name. The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()". The second parameter indicates how many milliseconds from now you want to execute the first parameter. Note: There are 1000 milliseconds in one second. Example When the button is clicked in the example below, an alert box will be displayed after 5 seconds. function timedMsg() { var t=setTimeout("alert('5 seconds!')",5000); } Example - Infinite Loop To get a timer to work in an infinite loop, we must write a function that calls itself. In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0. Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the button is pressed more than once: var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } The clearTimeout() Method Syntax clearTimeout(setTimeout_variable) Example The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer: var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } function stopCount() { clearTimeout(t); timer_is_on=0; } Example: Write a program that will countdown from 1 to 10 then it will display the word END in text box after the count down. SOURCE CODE: var c=1; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); if (c>=12) { document.getElementById('txt').value="END!"; } } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } JavaScript Events By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events: A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke onLoad and onUnload The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields.Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: JavaScript Try...Catch Statement The try...catch Statement The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax try { //Run some code here } catch(err) { //Handle errors here } Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error! Examples The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened: Example: var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.description + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } } The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing: Example: var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.isatumiagao.online/"; } } } The throw Statement The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. Syntax throw(exception) The exception can be a string, integer, Boolean or an object. Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error! The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed: Example var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) { throw "Err1"; } else if(x