setInterval多次触发函数

setInterval triggers function multiple times

本文关键字:函数 setInterval      更新时间:2023-09-26

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

我有一个函数,我使用Toastr创建在我的web应用程序上显示消息。我最终将把它与ajax请求绑定到API,以确定是否显示消息,但现在我只是测试它的外观。

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

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

我不能做setInterval(function(e){}作为e是未定义的,因为没有与它相关的事件,在点击,我已经使用e.p 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);

});

这是我的索引。phtml文件:

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

我所做的就是添加我想要运行到我的索引的javascript。php文件和toastr库。通过控制台。在日志间隔内,我得到三个日志。

这里有一个小提琴…不知道如何运行它,虽然它已经准备好了http://jsfiddle.net/efecarranza/rfvbhr1o/

确保将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()内,每次你动态地再次带来相同的页面,它在进程中双重设置setIntervalclearInterval功能没有帮助,直到你实际刷新浏览器。

setInterval将无休止地继续下去。我想你是在找setTimeout

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

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

如果它是,并且你不知道为什么(不知道你的代码我们也不知道),你可以在函数的开始像这样放置一个检查:

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

可能是错误的,你调用你的脚本两次我做了!在下面的代码中,我调用了两次'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>