简体   繁体   中英

Is it possible to have a variable interval within a javascript function?

I've been trying without success to set up a way of varying the interval used when incrementing a value by one. It's set to increment every 9 seconds but I'd like the counter to look a little less robotic and instead increment by a repeated variation of numbers, for example, 3 seconds, 7 seconds, 12 seconds, 10 seconds and 13 seconds (the five numbers add up to 45 to ensure an average of 9 seconds is maintained).

I've tried to put these numbers into an array and loop the value of 'interval' through them but I've now realised that value can't be changed within the context of the function once it's started.

Would be super grateful for any advice here. Thanks!

Current code for more 'robotic' count:

let interval = 9000;
let shiftCounter = {{ row.total }};

window.setInterval(function () {
  document.getElementById("shiftsCreated").innerHTML = shiftCounter.toLocaleString('en');
  shiftCounter = shiftCounter + 1;
}, interval); 

You can use setTimeout instead, and every time it completes, call new timeout by choosing random delay or whatever order you want.

let counter = 0;
const intervals = [3, 7, 10, 12]

increment(0);

function increment(timeout) {
    setTimeout(() => {
        console.log(`Counter: ${counter}.`)
        counter++;
        increment(intervals[Math.floor(Math.random() * intervals.length)] * 1000)
    }, timeout);
}

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