【问题标题】:setInterval triggers function multiple timessetInterval 多次触发函数
【发布时间】:2015-05-27 15:53:41
【问题描述】:

编辑:我所说的多次触发是指 newjob() 将触发 3 次,每 5 秒...所以在 20 秒内我将触发 12 次,而不是我会的 4 次想。所以它每 5 秒触发多次,而不是每 5 秒触发一次。

我有一个使用 Toastr 创建的函数,用于在我的 Web 应用程序上显示一条消息。我最终会将它与 API 的 ajax 请求联系起来,以确定是否显示消息,但现在我只是在测试它的外观。

我正在设置一个间隔,但它会多次触发其中的函数(通常是 3 次)。

$(document).ready(function() {
    setInterval(function () {
        newJob();
    }, 5000);
});

我不能做 setInterval(function(e) { } 因为 e 是未定义的,因为没有与之关联的事件,点击时,我使用 e.stopImmediatePropagation(); 让它只触发一次。 如果我没有 e,如何在设定的时间间隔内停止这种立即传播?

谢谢。

编辑:完整代码:

var newJob = function(e) {
    var i = -1;
    var $toastlast;

    var getMessage = function () {
        var msgs = ["There's a new job in the job dispatch queue", "A job pending approval has timed out"];
        i++;
        if (i === msgs.length) {
            i = 0;
        }

        return msgs[i];
    };

    var shortCutFunction = "success"; // 'success' or 'error'

    toastr.options = {
        closeButton: true,
        progressBar: true,
        debug: false,
        positionClass: 'toast-top-full-width',
        onclick: null,
        timeOut: "0",
        extendedTimeOut: "0",
        showDuration: "0",
        hideDuration: "0",
        showEasing: "swing",
        hideEasing: "linear",
        showMethod: "fadeIn",
        hideMethod: "fadeOut",
    };


    toastr.options.onclick = function () {
        window.location.href = "/dispatcher";
    };

    var msg = getMessage();

    $("#toastrOptions").text("Command: toastr["
                    + shortCutFunction
                    + "](\""
                    + msg
                    + "\")\n\ntoastr.options = "
                    + JSON.stringify(toastr.options, null, 2)
    );

    var $toast = toastr[shortCutFunction](msg);

};

$(document).ready(function() {
    setInterval(function () {
        console.log('set interval');
        newJob();
    }, 5000);


});

这是我的 index.phtml 文件:

    <?php
echo $this->headScript()->appendFile($this->basePath() . '/plugins/toastr/toastr.js')
echo $this->headScript()->appendFile($this->basePath().'/js/dispatchernotification.js');
    ?>

我所做的只是将我想要运行的 javascript 添加到我的 index.phtml 文件和 toastr 库中。 通过 console.loging 在间隔内,我得到三个日志。

这是一个小提琴..虽然它已经准备好了,但不确定如何运行它 http://jsfiddle.net/efecarranza/rfvbhr1o/

【问题讨论】:

  • 你的目标是什么? setInterval 意味着触发多次。
  • 根据您的代码,setInterval 每 5 秒触发一次。这不是你想要的吗?如果您只希望它触发一次,请改用setTimeout
  • 对不起,我的意思是说 newJob() 每 5 秒触发多次……所以每 5 秒,我会得到 3 个 newjob 实例
  • 你能在小提琴中重现这个问题吗?
  • NewJob() 函数的代码添加到您的问题中

标签: javascript jquery setinterval onready


【解决方案1】:

setInterval 将永无止境。我想你正在寻找setTimeout

【讨论】:

  • 抱歉,我的意思是说 newJob() 每 5 秒触发多次……所以每 5 秒,我会得到 3 个 newjob 实例
【解决方案2】:

setInterval:每隔 x 毫秒重复调用一个函数
setTimeOut:在 x 毫秒后调用一个函数。

你有两个选择:

在不再需要时清除间隔:

var intervalId;
$(document).ready(function() {
    intervalId = setInterval(function () {
        newJob();
    }, 5000);
});

// At some other point
clearInterval(intervalId);

或者,在您的情况下,更简单的解决方案是使用 setTimeout:

$(document).ready(function() {
        setTimeout(function () {
            newJob();
        }, 5000);
    });

【讨论】:

  • 我误解了正在发生的事情:我的 newJob 会在 setinterval 的“转”或“循环”中触发多次,因此它会每 5 秒触发多次,而不是每 5 秒触发一次
  • 您是否在某处重复了此代码?你的新工作功能是什么样的?
  • 我添加了完整的代码和小提琴,但不知道如何运行,因为它已经准备好了。
【解决方案3】:

确保将您的setInterval 放在$(document).ready(function() {...}) 之外。所以它会是这样的:

<script>

$(document).ready(function() {
    ... some code ...
});

var myInterval;
clearInterval(myInterval);
myInterval = setInterval(function() {
    ... your code is here ...
}, 5000);

</script>

由于某种原因,如果它在 $(document).ready() 内,则每次您再次动态地再次访问同一页面时,它都会将 setInterval 进行双重设置,而 clearInterval 函数在您实际刷新浏览器之前无济于事。

【讨论】:

    【解决方案4】:

    如果您可以在您的代码中添加一个 jsfiddle 会有所帮助,这样我们就可以准确地看到出了什么问题。无论出于何种原因,都可能多次调用 setInterval 函数。尝试在该函数的开头添加一个 console.log 语句来检查是否是这种情况。

    如果是这样并且您无法弄清楚原因(我们也不知道您的代码),您可以像这样在函数的开头进行检查:

    if (typeof this.installInterval.done == "undefined") {
      /*a bunch of code*/
      this.installInterval.done = true
    }
    

    【讨论】:

    • 预期的行为究竟是什么?您的代码设置方式,唯一会显示的消息是“作业调度队列中有一个新作业”。每次调用 newJob 时将 i 重置为 -1,即每 5000 毫秒一次。另外,请确保您在 jsfiddle 左侧的框架中选择 jquery,否则您的代码将无法正常工作。
    • 它在小提琴上运行良好,感谢您对 jquery 的澄清。可能是一个zend框架的东西或显示它两次的东西,我想我必须检查一下。我将其扩展为稍后通过 ajax 发布请求触发,ajax 将每隔几秒触发一次,根据 API 检查某些内容,然后在响应成功或失败时将显示不同的消息。
    【解决方案5】:

    您可能错误地像我一样调用了您的脚本两次! 在下面的代码中,我两次调用了“testLoop.js”。

    <script src="../js/testLoop.js"></script>
    <script type="text/javascript" src="../js/testLoop.js"></script>
    <script type="text/javascript" src="../js/cube.js"></script> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      相关资源
      最近更新 更多