Jquery setInterval() not working

前端 未结 5 2042
野性不改
野性不改 2020-12-20 16:30

I\'m trying to create a kind of slideshow.

The problem:

function slides(x) {
      $(\"#irack\").stop().animate({\"left\": x}, 20);
 };
setInterval         


        
相关标签:
5条回答
  • Shortest answer is:

    setInterval(function(){
       $("#irack").stop().animate({"left": -30}, 20)
    },300);
    
    0 讨论(0)
  • 2020-12-20 16:59

    The reason it doesn't work is because you're calling the function you're passing to setInterval

    You'll need to wrap the function in an anonymous function to pass a parameter as part of the interval.

    function slides(x) {
          $("#irack").stop().animate({"left": x}, 20);
     };
    setInterval(function(){slides(-30)},300);
    

    Note how the slides(-30) is now wrapped in an anon function.

    0 讨论(0)
  • 2020-12-20 17:03

    In you call to setInterval the slides method is being called inline change the call to as below:

    setInterval(function(){slides(-30);},300);
    
    0 讨论(0)
  • 2020-12-20 17:11

    Oh, I've found the problem :D

    $("#irack").stop().animate({"left": x}, 20);
    

    The problem is that "x" is a constant, and it changes the "left" to x and keeps it that way.

    I should do this way:

    x=$("#irack").offset().left+x;
    $("#irack").stop().animate({"left": x}, 20);
    

    And thanks a lot for pointing that "wrapping" stuff :D.

    0 讨论(0)
  • 2020-12-20 17:12

    You need to wrap the code to run at intervals in a function:

    function slides(x) {
          $("#irack").stop().animate({"left": x}, 20);
    };
    setInterval(function() {
        slides(-30);
    }, 300);
    

    Did you really mean setInterval? That will keep happening, every 300ms or so. If you want it just to happen once, use setTimeout instead.

    Update: If you want to cancel the interval later, you'll need to save the handle to a variable:

    // Somewhere appropriate, have a variable for the handle
    var handle = 0; // 0 = not running
    
    ...
    
    // Starting:
    handle = setInterval(...);
    
    ...
    
    // Stopping:
    if (handle != 0) {
        clearInterval(handle);
    }
    handle = 0;
    

    Note the use of 0 for the handle when it's not set. 0 is an invalid return value from setInterval, so you can rely on it. (You can use undefined or null if you like as well, just be sure to check for them.)

    0 讨论(0)
提交回复
热议问题