JavaScript timer and motion function encapsulation

catalogue

timer

Timer classification  

Timer setting

  Delay timer

  Use of delay timer

Intermittent timer

  Intermittent timer usage (countdown)

Timer clear

Clear delay timer

Clear intermittent timer

Encapsulation of motion function

Unidirectional uniform motion

Repeated uniform motion

  Simple packaging

Improvement of packaging

timer

Timer classification  

  • Delay timer: how long before execution (only once)

    • Application scenario: advertisement pop-up

  • Intermittent timer: it is executed once every few hours (it is always executed as long as it is not cleared)

    • Application scenario: rotation chart, countdown

Delay timer: generally, it supports a minimum value of 4ms
Intermittent timer: generally, it supports a minimum of 10ms  

Timer setting

  Delay timer

  • Basic syntax: setTimeout(fun,time)

    • fun: function, which can pass real name function or anonymous function

    • Time: time, in MS (omitted) 1s = 1000ms

  setTimeout(function(){
            console.log("Ha ha ha");
        },3000);


        function test(){
            console.log("Interesting");
        }

        setTimeout(test,6000);

  Use of delay timer

  Display the picture in 3 seconds and click the close button to close it

  <div>
        <img src="./img/11.jpg" alt="">
        <span>X</span>
    </div>
    <script>
        var div = document.getElementsByTagName("div")[0];
        var span = document.getElementsByTagName("span")[0];

        // set timer 
        setTimeout(function () {
            div.style.display = "block";
        }, 3000);

        span.onclick = function () {
            div.style.display = "none";
        }
    </script>

Intermittent timer

  • Basic syntax: setInterval(fun,time)

    • fun: function, which can pass real name function or anonymous function

    • Time: time, in MS (omitted) 1s = 1000ms

 // Intermittent timer
        // Pass anonymous function
        setInterval(function(){
            console.log("hello world");
        },1000);

        // Pass real name function
        function test1(){
            console.log("Hello");
        }
        setInterval(test1,3000);

  Intermittent timer usage (countdown)

The interface displays a ten second countdown  

  <span>10</span>
    <script>
        var span = document.getElementsByTagName("span")[0];
        
        var n = 10;

        // set timer 
        var timer =  setInterval(function(){
            n--;
            console.log(n);
            // judge
            if(n < 0){
                n = 0;
                // The clearing timer will not execute the next time, and the contents of the function body will be executed this time
                clearInterval(timer);
                console.log("ha-ha");
            }
            // assignment
            span.innerHTML = n;
        },1000);
    </script>

Timer clear

Clear delay timer

  • Basic syntax: clearTimeout(timerId);

    • timerId: the return value of the current timer, which is a unique value.

Clear intermittent timer

  • Basic syntax: clearInterval(timerId);
  • timerId: the return value of the current timer, which is a unique value.
var btns = document.getElementsByTagName("button");

// set timer 
var timer1 =  setTimeout(function(){
    console.log("Hahaha, I executed it in 5 seconds");
},5000);


var timer2 =  setInterval(function(){
    console.log("Hello");
},2000);

console.log(timer1,timer2);


// Clear timer
btns[0].onclick = function(){
    clearTimeout(timer1);
}

btns[1].onclick = function(){
    clearInterval(timer2);
}

Encapsulation of motion function

Unidirectional uniform motion

// Get element
var div = document.getElementsByTagName("div")[0];
var btn = document.getElementsByTagName("button")[0];


// Define a variable to hold the return value of the timer
var timer = null;

// Binding event div left 10 - > 1000
btn.onclick = function () {
    // Prevent the user from clicking multiple times and clear the timer before setting the timer
    clearInterval(timer);

    // set timer 
    timer = setInterval(function () {
        // Get the current style value first. For the getStyle function encapsulation, see the previous rendering style in the article
        var curVal = parseFloat(getStyle(div, "left"));

        // Add a fixed value on the original basis each time
        var speed = curVal + 10;

        // Clear timer
        if (speed >= 1000) {
            // Re assign speed because speed may be greater than the target value
            speed = 1000;
            clearInterval(timer);

        }

        console.log(timer);

        // set up
        div.style.left = speed + 'px';
    }, 50);
}
/*
    Purpose: get browser rendered styles
    @para:parameter
      eleObj:Element object
      attr:Style properties
    @return:Specific style values  

*/
function getStyle(eleObj, attr) {
    // Judge compatibility
    if (eleObj.currentStyle) { //Under IE
        return eleObj.currentStyle[attr];
    } else { //Non IE
        return getComputedStyle(eleObj)[attr];
    }
}

Repeated uniform motion

       // Get element
        var div = document.getElementsByTagName("div")[0];
        var btn = document.getElementsByTagName("button");


        // Define a variable to hold the return value of the timer
        var timer = null;

        // Binding event div left 10 - > 1000
        btn[0].onclick = function () {
            div.style.backgroundImage = "url('./img/right.gif')";
            // Prevent the user from clicking multiple times and clear the timer before setting the timer
            clearInterval(timer);
            // set timer 
            timer = setInterval(function () {
                // Get the current style value first
                var curVal = parseFloat(getStyle(div, "left"));

                // Add a fixed value on the original basis each time
                var speed = curVal + 10;

                //Target value reached clear timer
                if (speed >= 1000) {
                    // Re assign speed because speed may be greater than the target value
                    speed = 1000;
                    clearInterval(timer);
                }
                // set up
                div.style.left = speed + 'px';
            }, 50);
        }


        // 1000 -> 10
        btn[1].onclick = function () {
            div.style.backgroundImage = "url('./img/left.gif')";
            // Prevent the user from clicking multiple times and clear the timer first
            clearInterval(timer);
            // set timer 
            timer = setInterval(function () {
                // Get the current style value first
                var curVal = parseFloat(getStyle(div, "left"));

                // Reduce a fixed value on the original basis each time
                var speed = curVal - 10;

                //Target value reached clear timer
                if (speed <= 10) {
                    // Reassign speed
                    speed = 10;
                }

                // set up
                div.style.left = speed + 'px';
            }, 50);
        }
    </script>

  Simple packaging

  // Define a variable to hold the return value of the timer
        var timer = null;

        // Binding event div left 10 - > 1000
        btn[0].onclick = function () {
            move(div, "left", 10, 1000);
        }

        // 1000 -> 0
        btn[1].onclick = function () {
            move(div, "left", -10, 0);
        }
/*
    Function: uniform motion
    @para:parameter
        eleObj: Element object
        attr:Style properties
        step:step
        target:target value
*/

function move(eleObj, attr, step, target) {
    // Prevent the user from clicking multiple times and clear the timer first
    clearInterval(timer);
    // set timer 
    timer = setInterval(function () {
        // Get the current style value first
        var curVal = parseFloat(getStyle(eleObj, attr));

        // Add a fixed value on the original basis each time
        var speed = curVal + step;

     	//  Target value reached clear timer
        if ((speed >= target && step > 0) || (speed <= target && step < 0)) {
            // Reassign speed to the target value
            speed = target;
            // Clear timer
            clearInterval(timer);
        }

        // Set style values
        eleObj.style[attr] = speed + 'px';
    }, 50);
}

Improvement of packaging

 // Binding event div left 10 - > 1000
        btn[0].onclick = function () {
            move(div, "left", 10, 1000);
        }

        // 1000 -> 0
        btn[1].onclick = function () {
            move(div, "left", 10, 0);
        }
/*
         Function: uniform motion
         @para:parameter
             eleObj: Element object
             attr:Style properties
             step:step
             target:target value
     */

function move(eleObj, attr, step, target) {
    // Judge the positive and negative of step size
    //  If the initial value is less than the target value, step is positive, if the initial value is greater than the target value, step is negative
    step = parseFloat(getStyle(eleObj, attr)) < target ? step : -step;
    // Prevent the user from clicking multiple times and clear the timer first
    clearInterval(eleObj.timer);
    // Set the timer and save the return value of the timer on the custom attribute of the element
    eleObj.timer = setInterval(function () {
        // Get the current style value first
        var curVal = parseFloat(getStyle(eleObj, attr));

        // Add a fixed value on the original basis each time
        var speed = curVal + step;

        if ((speed >= target && step > 0) || (speed <= target && step < 0)) {
            // Reassign speed to the target value
            speed = target;
            // Clear timer
            clearInterval(eleObj.timer);
        }

        // Set style values
        eleObj.style[attr] = speed + 'px';
    }, 50);
}

Tags: Javascript

Posted on Thu, 04 Nov 2021 10:01:58 -0400 by darknessmdk