efecarranza
efecarranza

Reputation: 754

setInterval triggers function multiple times

EDIT: what i mean by fires multiple times, is that newjob() will fire 3 times, every 5 seconds...so in 20 seconds i'll have it 12 times triggered, instead of the 4 times that i would want. so it's triggeres multiple times every 5 seconds, instead of once every 5 seconds.

I have a function that i created using Toastr to display a message on my web application. i'm eventually going to tie it to an ajax request to an API to determine whether or not to display a message, but for now i'm just testing how it looks.

i am setting an interval, but it fires the function inside of it multiple times (usually 3).

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

i can't do setInterval( function(e) { } as e is undefined, as there is no event associated with it, on click, i've used e.stopImmediatePropagation(); to have it only fire once. how can i stop this immediate propagation on set interval if i don't have e?

thank you.

EDIT: full code:

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


});

and this is my index.phtml file:

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

all i'm doing is adding the javascript of what i want running to my index.phtml file and the toastr library. by console.loging inside interval, i get three logs.

here's a fiddle..not sure how to run it though as it's on ready http://jsfiddle.net/efecarranza/rfvbhr1o/

Upvotes: 4

Views: 17499

Answers (5)

CJay
CJay

Reputation: 36

May be by mistake you are calling your script twice as I did! In the code below I have called 'testLoop.js' two times.

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

Upvotes: 0

ekashking
ekashking

Reputation: 447

Make sure to put your setInterval outside of $(document).ready(function() {...}). So it will be like:

<script>

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

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

</script>

For some reason, if it's within $(document).ready() every time you dynamically bring the same page again it double-sets the setInterval in progression and clearInterval function doesn't help until you actually refresh the browser.

Upvotes: 5

evalunamain
evalunamain

Reputation: 46

It would help if you can add a jsfiddle with your code so we can see what's going wrong exactly. It's possible that for whatever reason the setInterval function is being called multiple times. Try adding a console.log statement at the start of that function to check if that's the case.

If it is and you can't figure out why (and neither can we without knowing your code), you could place a check at the start of the function like this:

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

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

setInterval: call a function repeatedly every x milliseconds
setTimeOut: call a function after x milliseconds.

You have two options:

Clear the interval when it isn't necessary anymore:

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

// At some other point
clearInterval(intervalId);

Or, the simpler solution in your case, use setTimeout:

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

Upvotes: 2

Jamie Barker
Jamie Barker

Reputation: 8246

setInterval will continue endlessly. I think you're looking for setTimeout.

Upvotes: 4

Related Questions