0

Need to set different time for each interval, Using like a variable?

$(document).ready(function()
{
    var refreshId = setInterval( function() 
    {
        //do something....
    }, need_custom_time_for_each_interval);
});
Tân
  • 1
  • 15
  • 56
  • 102

4 Answers4

1
function customSetTime(customTime) {
  setTimeout(function () {
    //do something....      
  }, customTime);
}

customSetTime(500); // example usage
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
chuu
  • 128
  • 6
0

Instead of setInterval you would probably want to call setTimeout from within the callback function. Then you could pass a custom value each time it executes.

Jason Miesionczek
  • 14,268
  • 17
  • 76
  • 108
0
const timeouts = [1000, 2000, 3000];
const timeout_fds = cb => timeouts.map(t => setTimeout(cb, t));
timeout_fds(() => console.log('Hey ', Math.random()))
Pawan Kumar
  • 1,443
  • 2
  • 16
  • 30
0

If you want to use setInterval function, you need to know the time when to reset your interval.

In this example, we create an interval with 500ms to print the id. When the id becomes to 10, we reset it by clearing the current interval and creating the new one.

$(document).ready(function()
{
    var id = 1;

    var refreshId;

    var implement = function() 
    {
        $('body').append('<div>' + id++ + '</div>');
        
        if (id === 10) {
            clearInterval(refreshId);
            
            refreshId = setInterval(implement, 100);
        }
        
        if (id === 20) {
            clearInterval(refreshId);
        }
    };

    refreshId = setInterval(implement, 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Tân
  • 1
  • 15
  • 56
  • 102