JavaScript Timing Events

Source: Internet
Author: User
Tags setcookie

By using JavaScript, you can execute code after a set interval of time, not immediately after the function is called. Called a timing event. It is easy to use timing events in JavaScript, and two key methods are:

    • SetInterval ()-interval specifies the number of milliseconds to execute the specified code continuously
    • SetTimeout ()-executes the specified code after pausing the specified number of milliseconds

Note: both setinterval () and settimeout () are the two methods of the HTML DOM window object.

SetInterval () method

The setinterval () interval specifies the number of milliseconds to execute the specified code, syntax:

    Window.setinterval (function () {alert ("Hello")},3000);//Popup Hello every 3 seconds

The Window.setinterval () method can use SetInterval () directly without using the window prefix. The first argument to SetInterval () is a function. The second parameter is the number of milliseconds in the interval. The following shows the current time.

     var  myvar=  setinterval (function () {mytimer},1000);    function  MyTimer () {        var  d = new  Date ();       var  t  = d.tolocaletimestring ();       document.getElementById ("Demo"). InnerHTML = t;                  }

Stop execution:

The Clearinterval () method is used to stop the function code executed by the SetInterval () method. Grammar:

Window.clearinterval (intervalvariable)

The method can also use the function clearinterval () Directly without using the window prefix. To use Clearinterval (), you must be a global variable when you create a timing method:

<p id= "Demo" ></p><button  onclick= "mystopfunction ()" >stop time</button><script> var  myVar = setinterval (function () {MyTimer ()},1000), function MyTimer () {   var  d  =  new  Date ( ) ;    var  t = d.tolocaletimestring ();    document.getElementById ("Demo"). InnerHTML = t;   }     function Mystopfunction () {      clearinterval (myVar);} </script>

SetTimeout () method

Window.settimeout (JavaScript  function, number of milliseconds);

The SetTimeout () method returns a value. In the above statement, the value is stored in a variable named T. If you want to cancel the setTimeout (), you can use the variable name to specify it. The first argument to SetTimeout () is a string containing a JavaScript statement. This one? "Alert (" 5 second! "), or a call to a function, such as alertmsg (), the second parameter is the number of milliseconds from the current to execute the first parameter.

How do I stop executing the settimeout () method?

The Cleartimeout () method is used to stop executing the function code of the SetTimeout () method.

Window.cleartimeout (timeoutvariable); timeoutvariable also needs to be a global variable.

JavaScript Cookies

A cookie is some data that is stored in a text file on a user's computer. When the Web server sends a Web page to the browser, the service side does not log the user's information after the connection is closed. A cookie is used to resolve how to log the client's user information: When a user accesses a Web page, his name can be recorded in a cookie. The next time the user accesses the page, the user's access record can be read in the cookie.

The cookie exists as a name/value pair, and when the browser requests a Web page from the server, the cookie belonging to the page is added to the request. The service side obtains the user's information in this way.

Create a cookie using JavaScript

JavaScript can use the Document.cookie property to create, read, and delete cookies. To create a cookie:

Document.cookie = "Username=zhang san";

You can also add an expiration time (in UTC or GMT) to the cookie. By default. The cookie is deleted when the browser is closed: document.cookie= "Username=zhang san;expires=thu,11 Sep 12:00:00 GMT"; You can also use the path parameter to tell the browser cookie where it is. By default, the cookie belongs to the current page.

Document.cookie= "Username=zhang san;expires=thu,11 Sep 12:00:00 GMT; path=/";

Using JavaScript to read cookies

In JavaScript, you can use the following code to read a cookie:

var  x = Document.cookie;

Document.cookie will return all cookies in the form of a string, type format: Cookie1=value;cookie2=value;cookie3=value;

Using JavaScript to modify cookies

In JavaScript, modifying a cookie is like creating a cookie:

Document.cookie= "Username=li si;expires= thu,11 Sep 12:00:00 gmt;path/";

The old cookie will be overwritten.

Delete cookies using JavaScript

Deleting cookies is very simple. Just ouch set the expires parameter to the previous time:

Document.cookie = "Username=;expires=thu,o1 Sep 00:00:00 GMT";

You do not have to specify a cookie value when deleting.

Cookie string

The Document.cookie property looks like a normal text string, but it is not. Even if a full cookie string is written in the Document.cookie, the cookie information is displayed as a name/value pair when the cookie information is re-read. If a new cookie is set, the old cookie will not be overwritten. The new cookie will be added to the document.cookie, so if you re-read Document.cookie, you will get multiple cookie name/value pairs: Cookie1=value;cookie2=value If you are looking for a specified cookie value, you must create a JavaScript function to look up the cookie value in the cookie string.

JavaScript Cookie Instance

In the following example, a cookie is created to store the visitor's name. First, the visitor accesses the Web page, and when he fills in the name, the name is stored in a cookie. Visitors will see a welcome message the next time they visit the page. This example creates 3 JavaScript functions: 1. A function to set the value of a cookie; 2. A function to obtain the value of a cookie; 3. function to detect cookie value

a function that sets the value of a cookie : the name of the person who stores the service.

    function   Setcookie (cname,cvalue,exdays)    {        var  d  = new Date ();        D.settime (D.gettime () + (exdays*24*60*60*1000));        var  expires  =  "expires=" + d.togmtstring ();       Document.cookie = cname + "=" + Cvalue + ";" +expires;         

Function Resolution: The value of the cookie named Cname,cookie is Cvalue, and the expiration time of the cookie is set expires.

function to get cookie value : Create a function The user returns the specified cookie value.

         function  GetCookie (CNAME)       {           var  name= cname + "=";           var  ca = Document.cookie.split (';');           for (var i = 0;i<ca.length; i++)          {              var  c = Ca[i].trim ();              if (c.indexof (name) ==0) {                   return  c.substring (name.length,c.length);                }               return  "";           }       }

Function Resolution: The parameter for the cookie name is CNAME. Creates a text variable to retrieve the specified cookie:cname + "=". Use a semicolon to separate the Document.cookie string, assign the delimited array of strings to the CA, loop the CA Array (i=0;i<ca.length;i++), and then read each value in the array and remove the front and back spaces (C=ca[1].trim ()). If a cookie (c.indexof (CNAME) ==0) is found, the value of the cookie (c.substring (name.length,c.length)) is returned. If no cookie is found, return "".

function to detect cookie values

Creates a function that detects whether a cookie is created. If a cookie is set, a greeting message is displayed. If you do not set a cookie, a pop-up window will be displayed to enter the visitor's name, and the call to the Setcookie function will store the caller's name for 365 days:

        function   Checkcookie ()       {           var   username = GetCookie ("username");           if (username!= "")            {                alert ("Welcome" +username);             }            else {               username = prompt ("Please enter your name", "");                   if (username!= "" &&username!=null) {                          Setcookie ("username", username,365);}}}           

JavaScript Timing Events

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.