JavaScript "marquee" lottery activity Code parsing and optimization (i)

Source: Internet
Author: User
Tags setinterval javascript array

A recent project has made a "marquee" lottery effect plugin. The previous article has been shared html with css the relevant knowledge. This article mainly shares some JavaScript-related knowledge. These days in writing this article, but also by the way to reconstruct their own code.
Here is the main way to write your own optimization process. Saying goes:

The progress of a program ape begins with dissatisfaction with one's own code.

Before you begin, take a look at the two missing questions and several knowledge points of the article, which you need to use in your own refactoring process:

1. Problems with 1px pixel line on the mobile side

For designers to my mobile Web page design is twice times the picture. In principle, when writing a Web page, the actual size of all objects will be except 2. But for a 1-megapixel floss?
Let's take a look at two graphs, the effect of the design draft:


The actual display effect under the Samsung S4:


Can see this time 1px line unexpectedly show out. the problem is related to the screen pixel density of the S4 phone. There are many articles about the relationship between screen pixel density and 1px line, which you can search for yourself. My solution here is to not handle the 1px line. Write as much as you like. Even if my base unit is rem , it is not another unit.

{    position: absolute;    width: 13rem;    height: 9.2rem;    border:1px solid #000;}
differences in fault tolerance between 2.PC browser and mobile-browser

Take a look at the code first:

$(‘[node-type=row-a‘).find(‘div‘);

It is clear that the selectors I use are syntactically incorrect. But what happens when you run in a browser? See:

It is clear that for the property selector, even if I have syntax errors, the PC-side browser can be correctly parsed. But on the phone side, this writing is not able to parse correctly, the code can not run.

So when writing code, be sure to pay attention to some small details ha ...

use of selectors in 3.jQuery

The most commonly used selectors in the process of using jQuery or Zepto are the following:

    $(‘div.testClass‘)

Just $() write the class or ID of the Dom node you need or use the attribute selector.
In view of the jquery documentation, $() there is a description for this:

jQuery([selector,[context]])

The most important thing is to look at the context description of (it is also one of the most easily overlooked, but very useful parameters we usually use):

By default, if you do not specify a context parameter, $ () looks for DOM elements in the current HTML document, and if you specify a context parameter, such as a DOM element set or JQuery object, it is found in this context. After jquery 1.3.2, the order of elements returned is equivalent to the order in which they appear in the context.

When I first started learning JavaScript, I heard that manipulating the DOM was a drain on browser performance, and traversing the DOM also affected program performance.
If we look for the Dom in the specified range, it will be much faster than looking for the whole document . and as we write Web Components, the components on a page can appear many times, so how do we tell which component we want to manipulate? This context parameter will play a role in determining the row. please continue to see Wow ...

4.jQuery Object-to-array conversion

When I first started studying jquery, I saw a word in a book:

The jquery object is a JavaScript array.

And in the process of using jquery, will encounter, JS object to jquery object, jquery object to JS object. There is no much introduction to these foundations.
But sometimes we want to use some native Array object methods or properties on the jquery object. Let's look at a simple example:

By running the results from the code in the diagram, you know that there is no way we want to use the jquery object reverse . Although test it is an array .
So what do we do to get jquery objects to use native Array object methods?

4.1 Using the prototype chain extension

For example, the following code:

jQuery.prototype.reverse=function(){    //一些操作}

prototypewhen using to extend the method, it has been considered as a disadvantage that it is possible to contaminate the existing prototype chain of methods. There is also the need to find the prototype chain when accessing the method.

4.2 Adding objects from a jquery object to an array

Look at the code below.

var test = $(‘div.test‘);var a=[];$(test).each(function(){    a.push($(this));});a.reverse();

This lets you flip the jquery object.

4.3 using the From () method of the Array object

This method is also used in the process of writing the plug-in itself. Take a look at the document description:

The Array.from () method converts a class array object or an iterative object to a real array.

Personal feeling using this code is more concise. It is not yet known whether there is a performance impact. Keep looking at the following code:

var test = $(‘div.test‘);varArray.from(test);a.reverse();
Effects of 5.setInterval () and settimeout () on program performance

Because setTimeout() the setInterval() implementation mechanism in JavaScript is exactly the same as the two functions, only the setTimeout() validation

So let's look at two pieces of code

var a ={    test:function(){        setTimeout(this.bbb,1000);    },    bbb:function(){        console.log(‘----‘);    }};a.test()

The output results are as follows:

See what the following code output is

var a ={    test:function(){        setTimeout(function(){            console.log(this);            this.bbb();        },1000);    },    bbb:function(){        console.log(‘----‘);    }};a.test();

Code error when running this code

From the above results we can know that when we use and, when used in the setInterval() setTimeout() rollback, this this The scope has changed, and pointed to window .

The meaning of SetTimeout (fn,0) is to specify that a task executes at the earliest available idle time of the main thread, that is, as early as possible. It adds an event at the end of the task queue, so it will not be executed until both the synchronization task and the task queue existing events are processed.

This means that after we have set up setTimeout (), it may not be immediately after the number of seconds to wait for the return, but will wait for the main thread to finish processing and then execute, so there is a "wait" more than their own set time phenomenon. There will also be other setTimeout () that already exist in the async queue and will wait until the previous one is executed before executing the current one.

Look at a Demo:

setTimeout(function bbb(){},4000);function aaa(){    setTimeout(function ccc(){},1000);}aaa();

If you run the above code and aaa() wait one second after execution, it will not execute immediately ccc() , but wait for the execution to execute and bbb() ccc() the end of the main thread run is 4s past.

JavaScript "marquee" lottery activity Code parsing and optimization (i)

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.