2

I have this code: (Stripped pieces not related to question)

$(function() {

mins = 0;  //Set the number of minutes you need
//secs = 0;

    function Decrement(mins){
        var secs = mins * 60;
        var currentSeconds = 0;
        var currentMinutes = 0;
        if(currentSeconds <= 9){ currentSeconds = "0" + currentSeconds; }
        secs--;
        document.getElementById("commercial").innerHTML = "Please wait "+currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
        if(secs !== -1){ alert("Done!"); }
    }

    function runCommercial(time){
        $('#commercial').html('Plase wait 8:00');
        $('#commercial').attr("disabled", "disabled");
        mins = 8;
        setInterval('Decrement(8)',1000);
    }

  $('#commercial').click(function(){
    runCommercial(30);
  });
});

Whenever I click the commercial button, the button text gets set to 8:00 as it should, altough it won't count down, instead it gives me "Decrement() is not defined" in the dev console of firefox. Why is this happening and how do I fix it?

Thanks.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Sven65
  • 29
  • 3

1 Answers1

7

This is happening because the String 'Decrement(8)' is being evaluated in the global namespace, not under your IIFE closure.

Change

setInterval('Decrement(8)',1000);

To

setInterval(function () {Decrement(8);}, 1000);

It's considered bad practice to cause an eval-style interpretation of code, try to always pass functions into setTimeout and setInterval, etc.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • I would also add that if decrement did not require a param (of 8). You could just call setInterval(Decrement,1000); – Buck3y3 Jan 08 '15 at 18:04