繁体   English   中英

全局变量不会改变

[英]Global variable won't change

我正在尝试设置一个计时器来关闭html页面上的模态。 问题是我需要在函数中使用全局变量,我不能为这个变量重新赋值。

我在许多网站上寻找答案,但它们都没有使用我的代码。 声明它时,该值是正确设置的,但是当我在函数中调用它时,它不能重新分配(而不是简单地减少它的值)。

浏览器的开发工具中没有检测到错误。

var delayToCloseModal = 5;

function AnimateModal() {

    // Each time this function is called
    delayToCloseModal = 5; // HERE IS THE PROBLEM!!!
                           // delayToCloseModal is not set at 5 again


    // If the modal isn't oppened
    if (document.getElementById("modal").style.opacity < 0.01) {
        // Open Modal
    }


    // Check every second if the timer is done, else reduce it by 1
    var checkTimer = setInterval(CheckCounterDone, 1000);


    function CheckCounterDone() {
        if (delayToCloseModal > 0) {
            // Reduce timer
            delayToCloseModal--; // Strangely, this works really fine!
        }
        else {

            // Stop checking timer
            clearInterval(checkTimer);

            // Close Modal

        }
    }
}

“计时器”系统工作正常,模态在打开后自动关闭5秒,但如果在模态已打开时再次调用该函数,则不会将打开计时器重置为5。

我找到了问题的解决方案! (它可能是“自制的”,但它有效)

我创建了一个布尔变量来启用或禁用setInterval的创建(如果已经运行)。 这是代码:

var delayToCloseModal = 5;
var timerRunning = false; // Set false as default value to allow the creation of the first timer

function AnimateModal() {

    // Each time this function is called
    delayToCloseModal = 5; 


    // If the modal isn't oppened
    if (document.getElementById("modal").style.opacity < 0.01) {
        // Open Modal
    }


    // Check if a timer is already running
    if (!timerRunning){
         var checkTimer = setInterval(CheckCounterDone, 1000); // Create new timer
         timerRunning = true; // Forbids to create another new timer
    }


    function CheckCounterDone() {
        if (delayToCloseModal > 0) {
            // Reduce timer
            delayToCloseModal--; 
        }
        else {

            // Stop checking timer
            clearInterval(checkTimer); // Delete the existing timer
            timerRunning = false; // Allow to recreate another timer

            // Close Modal

        }
    }
}

自上次调用函数以来,模态现在保持打开状态5秒,即使您对函数的调用进行垃圾邮件,计时器也只会减少一秒,并在延迟设置为0后成功关闭。

感谢所有为您提供帮助的人! :)

暂无
暂无

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

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