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

Adding simple delay to JavaScript code without using external libraries

本文关键字:JavaScript 代码 添加 延迟 简单 情况下 外部      更新时间:2023-09-26

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

我想它非常简单,但我是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代码,只用于点击时滚动。

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);
};