In JavaScript, why is it that when we use a timer to control the movement of an element, there are times when the element goes faster and more quickly.

Source: Internet
Author: User

When we are using the timer (setinterval), if we do not clear the timer, it will continue to operate continuously. Some people will ask, I only named a timer name, in the recall of the timer name, the timing device should start again ah, in fact, it is not the case. When we start a timer, the computer will open a timer for us, when we start the timer with the same name again, the computer will open another timer, independent of the previously opened timer, we called the name of the timer, it is just a variable, not the name of the timer, Its function is to clear the timer, that is, through the clearinterval (variable) to stop the timer operation. The code example is as follows:

Here's a function that controls the head of the element with the keyboard.

var timer;

function Keycontmove (flag) {

When calling the Customizer, the first time to clear the timer, if there is no such statement, each keystroke will call this function to open another timer, so that the head element will go faster
Clearinterval (timer);
Timer=setinterval (function () {
if (flag) {

The speedy is the y-axis velocity, and the speedx is the velocity in the x-axis direction.
Top+=speedy;
head.style.top=top+ ' px ';
}else {
Left+=speedx;
head.style.left=left+ ' px ';
}

},16)
}

Remember that the timer in the program is the return value, not the name of the timer!!!

In JavaScript, why is it that when we use a timer to control the movement of an element, there are times when the element goes faster and more quickly.

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.