Js setInterval 定时器笔记

var myTimer;
var speed = 100; //速度毫秒 值越小速度越快
var stepSpeed = 4; //值越大越快
$(function() {
    var mybox = $(".scroll_box");
    //向上
    $(".scroll_up").bind("mouseover", function() {
        var nowPos = mybox[boxCount].scrollTop; //当前值
        changePos(mybox, nowPos, 0);
    }).bind("mouseout", function() {
        if (myTimer) { window.clearInterval(myTimer); }
    });
    //向下
    $(".scroll_down").bind("mouseover", function() {
        var nowPos = mybox[boxCount].scrollTop; //当前值
        var maxPos = mybox[boxCount].scrollHeight - mybox.outerHeight(); //最大值
        changePos(mybox, nowPos, maxPos);
    }).bind("mouseout", function() {
        if (myTimer) { window.clearInterval(myTimer); }
    });
});

function changePos(box, from, to) {
    if (myTimer) { window.clearInterval(myTimer); }
    var temStepSpeed = stepSpeed;
    if (from > to) {
        myTimer = window.setInterval(function() {
            if (box[boxCount].scrollTop > to) { box[boxCount].scrollTop -= (5 + temStepSpeed); temStepSpeed += temStepSpeed; }
            else { window.clearInterval(myTimer); }
        }, speed);
    } else if (from < to) {
        myTimer = window.setInterval(function() {
            if (box[boxCount].scrollTop < to) { box[boxCount].scrollTop += (5 + temStepSpeed); temStepSpeed += temStepSpeed; }
            else { window.clearInterval(myTimer); }
        }, speed);
    }
}
原文地址:https://www.cnblogs.com/loongsoft/p/2921034.html