2015-02-09 58 views
-1

我想在運行該函數時更改setTimeout速度。setTimeout更改運行速度

我想即時通訊幾乎在那裏,還有一些東西在我的腳本上還沒有工作。但我無法弄清楚什麼。

有人可以幫助我嗎?

$('input[type="range"]').rangeslider({ 
     polyfill: false, 
     onInit: function() { 
     this.update(); 
    }, 
     onSlide: function(pos, value) { 
     tempPosition = pos + this.grabX; 
     position = (tempPosition <= this.handleWidth) ? this.handleWidth : (tempPosition >= this.maxHandleX) ? this.maxHandleX : tempPosition; 
     //timer = setTimeout(counter, value); 
     //clearTimeout(timer); 
     //var speed = value; 
     //clearTimeout(timer); 
     var timer = 0; 
     timer.length = 0; 
     timer = setTimeout(counter, value); 
     clearTimeout(timer); 
     document.getElementById("demo").innerHTML = timer; 


     //alert(counter); 
    } 
    }); 

    var counter = function() { 
    imagesArray[i].setOpacity(0.00); 
    i++; 
    if(i > 23){ 
     i = imagesArray.length - 23; 
    } 
    imagesArray[i].setOpacity(0.60); 
    speed = parseInt(speed); 
    setTimeout(counter, speed); 
    document.getElementById("test").innerHTML = speed; 
    }; 

    counter(); 

回答

1

首先,我會嘗試,並指出與您的代碼裏面的onSlide回調一些問題,您有:

var timer = 0; 
timer.length = 0; 
timer = setTimeout(counter, value); 
clearTimeout(timer); 

所以,每次使用滑塊時,您初始化局部變量timer爲0.您從不使用此值,因此這沒有意義。事實上,這足以打破你的邏輯,但也有其他問題。然後,您嘗試將timerlength屬性設置爲0.肯定會導致運行時錯誤?號碼沒有length屬性。然後你分配timer返回的setTimeout()的ID,這一切都很好,但是,那麼你立即清除超時,防止調度的執行被調度。

counter功能,而另一方面,自稱使用setTimeout,但返回的ID沒有捕捉到,這意味着該計劃調用不管你的onSlide回調裏面做什麼將被執行。

然後我看不到speed變量是在哪裏定義或設置的。

基本上,你的代碼有太多的問題要在答案的範圍內完成。一個健全的做法可能會是這個樣子:

var timer, speed; //Global, or at least in a scope shared by both the onSlide callback and the counter function 

$('input[type="range"]').rangeslider({ 
    ... 
    onSlide: function() { 
    clearTimeout(timer); //Cancel the currently pending execution of counter(); 
    speed = ... //Read value from slider 
    timer = clearTimeout(counter, speed); 
    }, 
    ... 
}); 

var counter = function() { 
    ... 
    timer = setTimeout(counter, speed); 
    ... 
}; 

值得一提的是這種方法,只要滑塊調整超時經過之前,計數器()不會得到執行。

+0

感謝這對我工作! – user3408380 2015-02-09 23:48:47