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);
});
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);
});
function customSetTime(customTime) {
setTimeout(function () {
//do something....
}, customTime);
}
customSetTime(500); // example usage
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.
const timeouts = [1000, 2000, 3000];
const timeout_fds = cb => timeouts.map(t => setTimeout(cb, t));
timeout_fds(() => console.log('Hey ', Math.random()))
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>