简体   繁体   English

使用SetInterval的函数的setTimeout延迟

[英]Javascript Delaying with setTimeout for a function that uses SetInterval

So I have an animation that works - showAlert that is called in body onload . 所以我有一个动画,可以在body onload showAlert Now I want to delay the animation for some time (1 second in the code snippet) using setTimeout . 现在,我想使用setTimeout将动画延迟一段时间(代码段中为1秒)。

I call delayShow() in body onload . 我在body onload调用delayShow()

function delayShow() {
    var runOnce = setTimeout(showAlert, 1000);
}

function showAlert() {
    var e = window.event;
    var element = e.target;

    var alert = document.getElementById("hide-navigation-instruction");

    var opacity = 0.0;

    function fadeIn() {
        opacity += 0.03;

        alert.style.opacity = opacity;

        if (opacity >= 1){
            clearInterval(id);
        }
    }

    var id = setInterval(fadeIn, 5);
}

The code does not work. 该代码不起作用。 If I change setTimeout to setTimeout(function(){alert("hello")}, 1000) , it will work. 如果我将setTimeout更改为setTimeout(function(){alert("hello")}, 1000) ,它将正常工作。

Anything I could do to set the delay? 我可以设置延迟吗?

Not sure why you have the lines 不确定为什么要排队

var e = window.event;
var element = e.target;

This is not the way to use events. 这不是使用事件的方式。 Either do further research on this topic or ask a specific new question about events in the context you want to use them. 可以对此主题进行进一步研究,或者在您要使用事件的上下文中询问有关事件的特定新问题。

The two lines above produce errors. 上面的两行会产生错误。 Finding the developer tools option within your browser will allow you to switch on the console which will show you the errors. 在浏览器中找到开发人员工具选项将使您能够打开控制台,该控制台将向您显示错误。

The following code works although the delay of 5 milliseconds in setInterval is too fast to be noticeable as a fade in. 尽管setInterval中的5毫秒的延迟太快而无法淡入,但以下代码仍然有效。

function delayShow() {
    /*added line below to ensure hide-navigation-instruction is hidden
      at start. You may have already set this within css style */
    document.getElementById("hide-navigation-instruction").style.opacity=0;
    var runOnce = setTimeout(showAlert, 1000);

}

function showAlert() {

    var alert = document.getElementById("hide-navigation-instruction");

    var opacity = 0.0;

    function fadeIn() {
        opacity += 0.03;

        alert.style.opacity = opacity;

        if (opacity >= 1){
            clearInterval(id);
        }
    }

    var id = setInterval(fadeIn, 5);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM