Brief Introduction to constant speed and variable speed (buffer) Movements in JavaScript

Source: Internet
Author: User
The movement of a div is actually a change in the distance between it and the browser border. If the speed of his change is certain, it is the constant speed. If the speed of the change is not certain, it is the variable speed. The movement of p is actually a change in the distance between his and the browser border. If the variable speed is fixed, it means constant speed. If the variable speed is not fixed, it means variable speed. When the change rate is proportional to the distance from the browser's border, p is buffering.
In fact, it is very simple to use a timer (timer) to change the border distance of the p-poly browser at intervals.

For example, uniform motion:

Enter the Timer: (every 30 ms)
If (whether to reach the end point)
{Stop timer}
Else do {Change distance}

The method of changing the distance determines whether the constant speed or variable speed (buffer) motion.

For example:

The Code is as follows:


Var timer = null;
Function startMove ()
{

Var oDiv = document. getElementById ('p1 ');
ClearInterval (timer );
Timer = setInterval (function (){
Var iSpeed = 1;

If (oDiv. offsetLeft >=300)
{
ClearInterval (timer );
}
Else
{
ODiv. style. left = oDiv. offsetLeft + iSpeed + 'px ';
}
}, 30 );
};



Buffer movement:

The Code is as follows:



Var timer = null;
Function startMove ()
{
Var iTarget = 300;

Var oDiv = document. getElementById ('p1 ');

ClearInterval (timer );
Timer = setInterval (function (){
Var iSpeed = (iTarget-oDiv.offsetLeft)/8;

ISpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed );

ISpeed = Math. ceil (iSpeed );
If (oDiv. offsetLeft = iTarget)
{
ClearInterval (timer );
}
Else
{
ODiv. style. left = oDiv. offsetLeft + iSpeed + 'px ';
}
Document. title = oDiv. style. left + ''+ iSpeed;
}, 30 );
};


In this way, a motion frame is ready! The principle is very simple, but it still needs to be improved. Come on!

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.