简体   繁体   中英

JavaScript 'setInterval()' not working as intended

If I just do changeImage(); it works fine, but I can't figure out how to get setInterval() to work. Here's my code:

HTML:

<div id="coin1"></div>

JS:

$(document).ready(function() {
  function changeImage() {
    if ($("#coin1").css("display") == "none") {  
      $("#coin1").fadeIn("slow");
    } else {  
      $("#coin1").fadeOut("slow");
    }
  };
  
  setInterval("changeImage()", 2000);
});

Because you're defining changeImage() within $(document).ready() , it isn't defined globally and therefore won't be called by setInterval. Use the function's name instead, ie:

setInterval(changeImage, 2000);

Hope this helps.

Just to be crystal clear, as the accepted answer does show the correct code but the explanation is incorrect, the issue is not that:

...you're defining changeImage() within $(document).ready() ...

It is completely fine for you to define functions within the scope of $(document).ready() .

The issue is that you're passing a string – setInterval("changeImage()", 2000); – as the first parameter to setInterval() instead of a function to be used as the callback. Per the accepted answer's code (but not explanation), the proper way to use setInterval() is like setInterval(changeImage, 2000); . Notice that parentheses are not used here. This is because you want to pass the function itself as the parameter, not whatever is returned by the function when it's called.

The only reason the code you're using happens to work when you move it outside of the scope of $(document).ready() is because when you do pass a string, the interpreter is forced to run an eval() against the string, and the eval() is happening in the global scope.

So while it is possible to have the solution work with a string, it is not good coding. Per the docs for setInterval() :

An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using eval() a security risk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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