setTimeout inside setInterval does not work well - javascript

My code should change the class of the item in every second and repeat it forever.
function myFunction() {
setInterval(function() {
$("#item").addClass("class-one").removeClass("class-two");
setTimeout(function(){
$("#item").addClass("class-two").removeClass("class-one");
}, 1000);
},1000);
}
myFunction();
First time the code works well, but after the loop starts again, it starts switching very fast. Can anybody tell me why?

The interval starts
1 second later the interval resolves:
classes are switched over
the timeout is triggered
1 second later:
The timeout resolves
classes are switched over
The interval resolves
classes are switched over
the timeout is triggered
You probably want the timeout time to be half the interval time, not the same as it.
A better approach entirely would be to use one class and use jQuery().toggle to toggle it on and off every second (using one interval and no timeouts).

correct way :
var i = 0;
function myFunction() {
setInterval(function() {
if(i % 2 == 0) {
$("#item").addClass("class-one").removeClass("class-two");
} else {
$("#item").addClass("class-two").removeClass("class-one");
}
i++;
},1000);
}
myFunction();
or with your solution : ( increase 1 second of setInterval time )
function myFunction() {
setInterval(function() {
$("#item").addClass("class-one").removeClass("class-two");
setTimeout(function(){
$("#item").addClass("class-two").removeClass("class-one");
}, 1000);
},2000);
}
myFunction();

Related

JavaScript: Set Interval not working

So basically I want to call a interval in a function while the function is being runned by another interval. This gives me the result I wasn't expecting. The console log should only be runned every third second but It's not.
My code:
// Define variable test
var test = 1;
// Setting function check on a 1000 ms interval
setInterval(function(){
check();
}, 1000)
// If our variable test is == 1, set another interval on 3000ms on next function
function check() {
if (test == 1) {
setInterval(function(){
execute();
}, 3000)
}
}
// Execute function
function execute() {
console.log("Called every 3rd second!");
}
How can I fix this, spent hours trying to find solution and I'm really exhausted and have no idea how to continue.
If you want to post a answer I really appreciate it! But try not to destroy the structure in the code.
Edit: If you have Chrome, you can run this script in the console. You have to wait a few seconds before it runs.
In case you need to run the function execute after every 3 seconds then you need to replace the first function setInterval with setTimeout. I am not sure why you need setInterval for the calling the check function.
Try out this code:
var test = 1;
// Setting function check on a 1000 ms interval
setTimeout(check, 1000)
// If our variable test is == 1, set another interval on 3000ms on next function
function check() {
if (test == 1) {
setInterval(execute, 3000)
}
}
// Execute function
function execute() {
console.log("Called every 3rd second!");
}

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);
}

settimeout being ignore, function is called instantly

function ShowColoursScreen() {
setSquaresList()
$("#ModeOne").hide();
$("#ModeTwo").show();
setTimeout(function () {
$("#ModeOne").show();
$("#ModeTwo").hide();
setTimeout(function () {
ShowColoursScreen();
}, 1500);
}, 15000);
}
This is very very weird, Im wanting to rotated between two divs every 15 seconds (i dont want to use js intervals). However after the first fifteen seconds ShowColoursScreen(); runs without waiting the second 15 seconds (if that makes sense). Its like the timeout gets ignored, any ideas?
Your code is correct. However, the inner timeout just waits for 1.5 seconds as you forgot a zero. Simply replace the 1500 with 15000.
You can also simplify the call a bit - as you do not have any arguments there is no need for the anonymous function: setTimeout(ShowColoursScreen, 15000);
function ShowColoursScreen($elements) {
if(!$elements instanceof jQuery) {
$elements = $($elements);
}
var current = 0;
// What does this function do?
setSquaresList();
function showCurrent () {
var $currentElement = $($elements[current]);
$elements.not($currentElement).hide();
$currentElement.show();
(current++) % $elements.length;
setTimeout(showCurrent, 15000);
}
showCurrent();
return $elements;
}
ShowColoursScreen('#ModeOne, #ModeTwo')

Why isn't clearInterval working in this code?

There is a function which sets an interval using setInterval(), but even after calling clearInterval(), I can see in the console that the else condition is still running. How can I clear that interval properly?
function increase(old, step, neu) {
var i = 0;
var delay2;
function countUp() {
if (i < 5) {
old += step;
// console.log("increase")
$("#total-price-value").text(old + " dollors");
$("#total-price-value").digits();
i++;
delay2 = setInterval(countUp, 80);
} else {
clearInterval(delay2);
console.log(delay2);
}
}
countUp();
}​
It looks like you're a little confused about the difference between timeouts and intervals. Timeouts fire only once; intervals fire many times. If you're using an interval, you probably only want to set it once (you're setting it every time). If you're using a timeout, you probably want to set it every time (like you're doing).
In order to fix the problem, you'll either want to switch to timeouts (probably the easiest; just a search/replace) or only set the interval once.
For example, here is how one might use setTimeout to count up to five:
var count = 0;
function timeoutFired() {
count++;
if(count < 5) {
setTimeout(timeoutFired, 1000);
}
}
setTimeout(timeoutFired, 1000);
Using timeouts, we don't need to clear to stop it from counting; simply not setting a timeout will prevent it from running again.
Here is how one might use setInterval:
var count = 0;
function intervalFired() {
count++;
if(count >= 5) {
clearInterval(interval);
}
}
var interval = setInterval(intervalFired, 1000);
If you want some code running periodically using intervals to stop, you must call clearInterval. Note that we only call setInterval once, versus setTimeout every time we didn't want it to continue.
Apparently, you have mistaken setInterval for setTimeout. setInterval runs the enclosed function every n milliseconds while setTimeout executes only once after n milliseconds.
I suppose you wanted to "tick until 5" so here's a sample:
function increase(old, step, neu) {
var i = 0;
interval = setInterval(function() {
if (i < 5) {
//do something at this "tick"
console.log(i);
i++;
} else {
//else, stop
clearInterval(interval);
}
},80);
}
increase();

How can I call a function every 3 seconds for 15 seconds?

How do I call a jQuery function every 3 seconds?
$(document).ready(function ()
{
//do stuff...
$('post').each(function()
{
//do stuff...
})
//do stuff...
})
I'm trying to run that code for a period of 15 seconds.
None of the answers so far take into account that it only wants to happen for 15 seconds and then stop...
$(function() {
var intervalID = setInterval(function() {
// Do whatever in here that happens every 3 seconds
}, 3000);
setTimeout(function() {
clearInterval(intervalID);
}, 18000);
});
This creates an interval (every 3 seconds) that runs whatever code you put in the function. After 15 seconds the interval is destroyed (there is an initial 3 second delay, hence the 18 second overall runtime).
You can use setTimeout to run a function after X milliseconds have passed.
var timeout = setTimeout(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
Or, setInterval to run a function every X milliseconds.
var interval = setInterval(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
setTimeout and setInterval return IDs, these can be used to clear the timeout/interval using clearTimeout or clearInterval.
setInterval(function() {
// Do something every 3 seconds
}, 3000);
Use the setInterval function.
var doPost = function() {
$('post').each(function() {
...
});
};
setInterval(function() { doPost(); }, 3000);
You could use the setTimeout method also, which supports things like cancelling the timer.
See: http://msdn.microsoft.com/en-us/library/ie/ms536753(v=vs.85).aspx

Categories