change the speed of setInterval in the second round - javascript

I am trying to change the speed of the interval for calling a function.
The first time it should take a second, and the rest should take nine seconds to call.
var tiempoCaratula=1000;
var refreshCaratula = setInterval(function() {
$('.col-2').load('caratula.php');
}, tiempoCaratula);

Run the first one using setTimeout and then schedule it for future runs in whatever interval you need to.
var myFunction = function() {
$('.col-2').load('caratula.php');
}
var refreshCaratula;
// call the function after 1000ms
setTimeout(function () {
myFunction();
// then schedule it to run every 9000ms
refreshCaratula = setInterval(myFunction, 9000);
}, 1000);

You could make a timeout that runs once at one second and a sub interval that runs every nine seconds after the timeout.
var tiempoCaratula = 1000;
var tiempoCaratula2 = 9000;
var refreshCaratula = setTimeout(function() {
$('.col-2').load('caratula.php');
var refreshCaratula2 = setInterval(function() {
$('.col-2').load('caratula.php');
}, tiempoCaratula2);
}, tiempoCaratula);

Related

Can you update setInterval variable while it runs

I need to modify existing slider. Its slides now have differing data-seconds added to it and need be active that long. Previously I had:
var slidePause = 10;
function startSlideBanner() {
bannerTimer = setInterval(nextSlide, slidePause * 1000);
}
startSlideBanner();
Which worked infinitely well. Now I would need to update slidePause variable every iteration. Looking for an example if its possible.
No: You cannot do it with setInterval. Once it is set, it may only be cancelled.
What you can do however, is use setTimeout to achieve your goals. While this can be done recursively, I prefer to take advantage of promises to do it iteratively:
const wait = ms => new Promise(res => setTimeout(res, ms));
let slidePause = 10;
async function startSlideBanner() {
while(true) {
await wait(slidePause * 1000);
nextSlide();
// Example: Double the time for each slide
slidePause = slidePause * 2;
}
}
startSlideBanner();
One of the problems with setInterval() is that JavaScript's single threaded nature can result in uneven periods between the setInterval() code being fired. To avoid this, run setInterval() at a faster rate, and calculate the time passed to determine whether an action should be taken.
If you make the calculation for time passed dependent on a variable you can change the effective rate at which the event occurs.
function nextSlide(period){
console.log("Next Slide in "+period);
}
function VariableTimer(period, startImmediately = true) {
this.period = period;
self = this;
this.startTime = startImmediately?0:Date.now();
this.time = setInterval(function(){
if (Date.now()-self.startTime > self.period*1000) {
self.startTime = Date.now();
nextSlide(self.period);
}
}, 100); // Run setInterval at 100ms intervals.
this.stop = function(){
clearInterval(self.time);
}
}
let timer = new VariableTimer(10);
// Change the timer period like this
// timer.period = 5;
// After 20 seconds switch to 5 second intervals
setTimeout(function(){timer.period = 5;},20000);
// After 40 seconds, stop the timer.
setTimeout(function(){timer.stop();console.log("timer stopped")}, 40000);

Changing a global variable inside a function, to change the setInterval's second parameter [duplicate]

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 3 years ago.
I have a global variable called interval, and I need to change this global variable to 5000 inside a function, so after waiting for 1 second, the setInterval function will now wait for 5 seconds. However, when I tried the code below, it only waits 1 second every time it's executed.
var timeToWait1 = 1000;
var timeToWait2 = 5000;
var interval = timeToWait1;
setInterval(function(){ waitFunction () }, interval);
function waitFunction() {
interval = timeToWait2;
} //end of function waitFunction()
Interval is set once and can't be changed, You'd need timeout.
var timeToWait1 = 1000;
var timeToWait2 = 5000;
setTimeout(waitFunction, timeToWait1);
function waitFunction() {
console.log('waitFunction called');
setTimeout(waitFunction, timeToWait2);
}
Once an interval has started, you can't change the duration it uses. You'll have to stop the interval and re-start it with the new duration.
let intervalId;
let makeInterval = duration => {
console.log('making a new interval');
intervalId = setInterval(waitFunction, duration);
};
makeInterval(1000);
function waitFunction() {
clearInterval(intervalId);
console.log('waitFunction running');
makeInterval(5000);
}
You might consider using a recursive setTimeout instead, to avoid the need for clearing:
let makeTimeout = duration => {
console.log('making a new timeout');
setTimeout(waitFunction, duration);
};
makeTimeout(1000);
function waitFunction() {
console.log('waitFunction running');
makeTimeout(5000);
}

javascript timer counting very fast as time passes

I want a counter which reset in specific interval of time. I wrote this code. When I refresh the page it is executing perfectly. But as time passes the timer goes really fast, skipping seconds. Any idea why this is happening.
function countdown_new() {
window.setInterval(function () {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter) - eval(1);
$("b[id=show-time]").html(updateTime);
if (updateTime == 0) {
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(countdown_new());
// countdown_new();
//my_ajax();
}
}, 1000);
}
window.setInterval(function () {
countdown_new();
}, 5000)
HTML
Coundown in 5 seconds
The issue is because you are not clearing the previous timer before starting a new one, so you start a new one for each iteration. To clear the timer you should save a reference to it, and pass that to clearInterval, not a function reference.
Also, note that your pattern of using multiple intervals for different operations can lead to overlap (where two intervals are acting at the same time and cause odd behaviour). Instead, use setTimeout for the initial 5 second delay and then chain further calls to stop this overlap.
Try this:
var timer;
function countdown_new() {
timer = setInterval(function () {
var $showTime = $("#show-time")
var updateTime = parseInt($showTime.text(), 10) - 1;
$showTime.html(updateTime);
if (updateTime == 0) {
$showTime.html('5');
clearInterval(timer);
setTimeout(countdown_new, 5000);
}
}, 1000);
}
setTimeout(countdown_new, 5000);
Example fiddle
Note that you should use the # selector to select an element by its id attribute, and you should never use eval - especially not for type coercion. To convert a value to an integer use parseInt().
You are calling window.setInterval(), which schedules a function call to countdown_new() ever 5 seconds without stop.
Compounding the problem, you are calling countdown_new() again inside your clear interval.
You need to call setInterval just once to continuously execute a function every 5 seconds.
If you want to cancel an interval timer, you need do to this:
var intervalObj = setInterval(function() { ... }, 5000);
clearInterval(intervalObj);
Yes clearinterval does the trick.
function countdown_new(){
t = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(t);
// countdown_new();
my_ajax();
}
}, 1000);
}

setInterval function looping too fast

I have similar code to what is below and the setInterval is running a lot faster than 1000ms and it crashes/ slows down the page.
var checkDiffTest = function(){
console.log('test checkDiff init');
var interval = setInterval(countdownTest(), 1000);
}
var countdownTest = function(){
console.log('test countdown init');
checkDiffTest();
}
countdownTest();
You are setting a new interval each time the interval runs:
Your interval calls countdownTest()
Which called checkDiffTest()
Which creates a new interval (while the last one is still running)
A new 1000ms interval is started every 1000ms.
It looks as though you want setTimeout() instead.
Also countdownTest() as setInterval's first parameter invokes that function straight away. You want to pass the function as reference:
var checkDiffTest = function(){
console.log('test checkDiff init')
var interval = setTimeout(countdownTest, 1000);
}
var countdownTest = function(){
console.log('test countdown init');
checkDiffTest();
}
countdownTest();

Increase the value of a number in an element every x milliseconds

So I have this simple HTML:
<span id="badge">0</span>
I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?
Thanks a bunch - I'm new to this :)
You should do this:
<script>
var $badge = $('#badge'); // cache
setInterval(function () {
var value = parseInt($badge.html());
value++;
$badge.html(value);
}, 1000);
</script>
Assuming 1000 milliseconds.
function increment() {
document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
setTimeout("increment()",3000);
}
increment()
Every of the answers I see here has the same drawbacks:
performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
setInterval() is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.
I would code:
var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
textNode.data = Math.round((new Date()-start)/ms);
}, ms);
If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.
var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast
Something like this?
var millisecs = 10;
setInterval(function() {
var $badge = $('#badge');
$badge.text(parseInt($badge.text())++);
}, millisecs);
http://jsfiddle.net/iambriansreed/MPP8n/3/
Check this http://www.w3schools.com/js/js_timing.asp
A little more about timers:
// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs
// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second
// to "turn off" timer
clearInterval(tmrChangeI);
// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;
// establish function to execute
function tmrFunc() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};
// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);
// clear via bool allowing one more execution
tmrBool = false;
// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short
// and maybe overriden by bool still being true, this is not safest
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);
You can use setInterval.
var $badge = $('#badge');
setInterval(function () {
$badge.html(parseInt($badge.html()) + 1);
}, 1);​//Specify the milliseconds here, right it will update the value every 1 millisecond
Working demo - http://jsfiddle.net/8FMZh/
You could create a Jquery plugin, so you can reuse whenever you need.
$.fn.increment= function(options) {
var $this = $(this);
var coef = options.coef;
var speed = options.speed;
var value = 0;
setInterval(function(){
value = value + coef ;
$this.html(value);
}, speed);
};
And in your main javascript file :
$("#badge").increment({coef: 1, speed:1000});
working demo : http://jsfiddle.net/8FMZh/102/

Categories