简体   繁体   English

在Javascript中更新setInterval函数的毫秒参数

[英]Updating the millisecond parameter of setInterval function in Javascript

I have a slider that is displaying quotes. 我有一个显示报价的滑块。 Some quotes are longer than others and I'd like to provide the user adequate time to read them. 有些报价比其他报价更长,我想为用户提供足够的时间来阅读它们。 The timer variable is getting updated in the changeQuote function, but its not updating the paramater of the setInterval function. 在changeQuote函数中,timer变量正在更新,但不会更新setInterval函数的参数。 How can I update the milliseconds parameter of the setInterval? 如何更新setInterval的毫秒参数? Thanks 谢谢

var quotes=[{quote:'lorem ipsum', name:'test'},{quote:'lorem ipsum ipsum 2', name:'test2'}];

var x=0;
var l = quotes.length;
var ql=0;
var timer=0;

function quoteInit(){
    if(x==l) x=0;
    ql = quotes[x]['quote'].length;
    $('.quote').find('h4').html(quotes[x]['quote']);
    $('.quote').find('p').html(quotes[x]['name']);
    timer=(ql*110);
    x++;
    changeQuote(timer); 
}

function changeQuote(timer){
    console.log(timer);
    setInterval(quoteInit,timer);
}

quoteInit();

Adding to my comment, use something like this to stop and start your timer again: 在我的评论中添加以下内容,以停止并重新启动计时器:

function start() {
    theTimer = setInterval(quoteInit,timer);
};

function stop() {
    clearInterval(theTimer);
};

Simply call stop() and start() when you want to reset the timer with a different interval (after changing timer ofcourse). 要以不同的时间间隔重置计时器(在更改课程timer之后stop() ,只需调用stop()start()即可。 This will stop the timer (with your old timer value) and start it again with the new value. 这将停止计时器(使用您的旧timer值),然后使用新值再次启动它。

As everybody said, just changing setInterval to setTimeout works fine: 就像大家说的那样,只需将setInterval更改为setTimeout

 var quotes=[{quote:'short', name:'test'}, {quote:'medium ipsum', name:'test2'},{quote:'long lorem ipsum ipsum', name:'test3'}]; var x=0; var l = quotes.length; var ql=0; var timer=0; function quoteInit(){ if(x==l) x=0; ql = quotes[x]['quote'].length; $('.quote').find('h4').html(quotes[x]['quote']); $('.quote').find('p').html(quotes[x]['name']); timer=(ql*110); x++; changeQuote(timer); } function changeQuote(timer){ console.clear(); console.log(timer); setTimeout(quoteInit,timer); } quoteInit(); 
 body{ font-family: Arial, Helvetica, sans-serif; text-align: center; } h4{ font-size: 2em; font-weight: 700; margin: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="quote"> <h4></h4> <p></p> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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