在不使用外部库的情况下为JavaScript代码添加简单延迟

时间:2016-01-05 15:17:00

标签: javascript delay

一个简单的问题,请告诉我如何为此代码添加延迟。

我想这很简单,但我是JavaScript新手。 我认为答案是在持续时间变量的开头某处。

这是JavaScript代码:

var modern = requestAnimationFrame, duration = 400, initial, aim;

window.smoothScroll = function(target) {
var header = document.querySelectorAll('.aconmineli');
    aim = -header[0].clientHeight;
    initial = Date.now();

  var scrollContainer = document.getElementById(target);
  target = document.getElementById(target);

    do {
    scrollContainer = scrollContainer.parentNode;
    if (!scrollContainer) return;
    scrollContainer.scrollTop += 1;
    }
    while (scrollContainer.scrollTop == 0);

    do {
    if (target == scrollContainer) break;
    aim += target.offsetTop;
    }
    while (target = target.offsetParent);

    scroll = function(c, a, b, i) {

        if (modern) {
        var present = Date.now(),
        elapsed = present-initial,
        progress = Math.min(elapsed/duration, 1);
        c.scrollTop = a + (b - a) * progress;
        if (progress < 1) requestAnimationFrame(function() {
        scroll(c, a, b, i);
        });
        }
        else {
        i++; if (i > 30) return;
        c.scrollTop = a + (b - a) / 30 * i;
        setTimeout(function() {scroll(c, a, b, i)}, 20);
        }
    }

    scroll(scrollContainer, scrollContainer.scrollTop, aim, 0);
}

顺便说一下,它是一个很棒的纯JavaScript代码,用于滚动点击。

1 个答案:

答案 0 :(得分:1)

var modern = requestAnimationFrame,
    duration = 400,
    initial,
    aim,
    delay = 1000;

window.smoothScroll = function(target) {
    setTimeout(function() {
        window.doSmoothScroll(target);
    }, delay);
};

window.doSmoothScroll = function(target) {
    var header = document.querySelectorAll('.navbar');
    aim = -header[0].clientHeight;
    initial = Date.now();

    var scrollContainer = document.getElementById(target);
    target = document.getElementById(target);

    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    }
    while (scrollContainer.scrollTop === 0);

    do {
        if (target == scrollContainer) break;
        aim += target.offsetTop;
    }
    while (target == target.offsetParent);

    scroll = function(c, a, b, i) {

        if (modern) {
            var present = Date.now(),
                elapsed = present - initial,
                progress = Math.min(elapsed / duration, 1);
            c.scrollTop = a + (b - a) * progress;
            if (progress < 1) requestAnimationFrame(function() {
                scroll(c, a, b, i);
            });
        } else {
            i++;
            if (i > 30) return;
            c.scrollTop = a + (b - a) / 30 * i;
            setTimeout(function() {
                scroll(c, a, b, i);
            }, 20);
        }
    };

    scroll(scrollContainer, scrollContainer.scrollTop, aim, 0);
};