How to set setInterval period as variable and to remove waiting time? - javascript

I have a table with checkbox in each row. When the checkboxes are checked, the function will loop through to update the status of each row.
here is my working fiddle: http://jsfiddle.net/qJdaA/2/
I used setInterval() to loop the function. as the table is dynamic, i do not know how long the list is going to be. so i set the period as a variable index*4000 as follow:
$('#monitor').click(function () {
$('#monitor').attr('disabled','true');
bigloop=setInterval(function () {
var checked = $('#status_table tr [id^="monitor_"]:checked');
if (checked.index()==-1){
$('#monitor').attr('disabled','true');
}else{
(function loop(i) {
$('#monitor').removeAttr('disabled');
//monitor element at index i
monitoring($(checked[i]).parents('tr'));
//delay
setTimeout(function () {
//when incremented i is less than the number of rows, call loop for next index
if (++i < checked.length) loop(i);
}, 3000);
}(0)); //start with 0
}
}, index*4000);
however, the problem is that it will wait for the first loop to get over without doing anything. let say i have 10 items in the list, then it will wait for 40 seconds before doing its task. How can i eliminate that problem?
Then if out of the 10 items, only 1 row is checked, i have to wait 40 seconds to update just that one row, which is inefficient.
I have tried to set var clength = checked.length and use it to multiply with 4000. but it won't work. Why and how should i do it?

Example how to remove interval
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
// do things here
}
function myStopFunction()
{
// clear interval here
clearInterval(myVar);
}
</script>
Or
<script>
var myVar=setInterval(myTimer,1000);
function myTimer()
{
// do things here
}
function myStopFunction()
{
// clear interval here
clearInterval(myVar);
}
</script>

Related

Javascript clearInterval does not stop setInterval

I have a javascript code that shows some messages every 6 seconds using setInterval function as bellow:
$(function () {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "Offer accepted.</h1>"];
setInterval(function () {
$(".lead").fadeOut(400, function () {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if(count === 3){
clearInterval(window.location.href = "www.mydomain.com");
}
count++;
}, 6000);
});
When the last message is displayed I want to redirect to a URL so I checked the counter and placed a clearInterval when the last message is displayed however it does not go to the url right after the last massage is displayed but geos back to the first one and then redirect, sounds like it continues to loop. How can I fix that please?
Thanks
An interval id is returned by setInterval , you need to use that to stop particular interval.
$(function() {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "<h1>Offer accepted.</h1>"];
var intervalTimer = setInterval(function() {
$(".lead").fadeOut(400, function() {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if (count === 3) {
clearInterval(intervalTimer);
}
count++;
}, 6000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lead"></div>

How to change the interval dynamically when using setInterval

I have this fiddle : https://jsfiddle.net/reko91/stfnzoo4/
Im currently using Javascripts setInterval() to log a string to console.
What I want to do, is in this setInterval function check whether the interval variable has changed, if it has, change the interval in the setInterval function. I can lower the interval variable by 100 (speeding the function up) by a click a button.
Is this possible ?
Someone mentioned this : Changing the interval of SetInterval while it's running
But this is using a counter, so they only run it a certain amount of times. I need to run it for however long, but change how fast the function gets called again.
Here is the code :
var interval = 2000;
setInterval(function() {
interval = getInterval();
console.log('interval')
}, interval);
function getInterval() {
return interval;
}
$('#speedUp').on('click', function() {
interval -= 100;
console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
speed up
</button>
I would just stop the interval and start a new one with the different timing
var interval = 2000;
var intervalId;
// store in a function so we can call it again
function startInterval(_interval) {
// Store the id of the interval so we can clear it later
intervalId = setInterval(function() {
console.log(_interval);
}, _interval);
}
function getInterval() {
return interval;
}
$('#speedUp').on('click', function() {
interval -= 100;
// clear the existing interval
clearInterval(intervalId);
// just start a new one
startInterval(interval);
console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
speed up
</button>

Exit popup + setInterval

I'm trying to create something like Exit Popup but limited to users residing on my page less than 10 seconds. I thought to use setInterval:
var counter = 0;
var myInterval = setInterval(function () {
// count
console.log(counter);
// Clear if more than 10 seconds
if ( 10 < counter ) {
console.log('Stop setInterval');
clearInterval(myInterval);
}
++counter;
}, 1000);
if ( 10 > counter ) {
// Simplified exit popup function
$(window).mouseleave(function() {
console.log('Popup');
clearInterval(myInterval);
});
}
First part of code works, but the second part executes even if counter is greater than 10. Why this is not working as it should?
No need for a counter. Just bind the event at page load, and unbind it after X seconds using a setTimeout:
$(window).bind('mouseleave', exitPopup);
setTimeout(function(){
$(window).unbind('mouseleave', exitPopup);
},10000);
function exitPopup(){
alert('Exit popup');
}
JS Fiddle Demo (3 seconds)
For this demo, make sure to put your cursor in the lower right window right at the beginning, and wait 3 seconds. It should not appear after that. If you don't wait, it'll show the popup.

Execute two functions alternately and infinitely in javascript with delay

I have four divs that I want to show one after the other by hiding the previous one. I use a counter with modulo operator to select the divs for displaying. So I require to execute my functions in the following way.
function show_div(counter)
***after delay***
function hide_div(counter)
***after delay***
function show_div(counter+1)
***after delay***
function hide_div(counter+1)
***after delay***
function show_div(counter+2)
How can I achieve this?
A short solution:
show_div(0);
function show_div(counter) {
// code here
setTimeout(hide_div, 2000, counter);
}
function hide_div(counter) {
// code here
setTimeout(show_div, 2000, (counter + 1) % 4);
}
You could use setInterval():
var counter = 0;
var divVisible = false;
function toggleDiv() {
if (divVisible) {
hide_div(counter);
counter = (counter + 1) % 4;
divVisible = false;
} else {
show_div(counter);
divVisible = true;
}
}
window.setInterval(toggleDiv, 1000);
First time it is run, the counter is 0 and divVisible is false, so it will show the div and flip the boolean divVisible. Next time (after 1000ms), it will hide the div, increase counter, then flip the boolean divVisible again. And so it will continue forever for your 4 divs.
You can use setTimeout.
setTimeout(function(){show_div(counter)},delay)
But be careful. If using a while loop, you need to a separate function that creates the timeout, due to variable scope.
function timeout(func, args, delay){
setTimeout(function(){func(args)}, delay);
}
var counter = 0
while(1){
timeout(show_div, counter, counter*500);
timeout(hide_div, counter, counter*500+500);
counter++;
}
An alternative solution would be some sort of chaining function:
function show(delay, counter){
setTimeout(function(){
show_div(counter);
},delay);
setTimeout(function(){
hide_div(counter);
show(delay, counter+1);
},delay*2);
}
This uses setTimeout to call other setTimeouts when it is finished. This will use less memory than the other solution.
You can do it this way:
var divs = $('.someClass'),
numOfDivs = divs.length,
delay = 500,
index = -1;
showNextDiv();
function showNextDiv(){
index = (index == numOfDivs-1) ? 0 : ++index;
divs.eq(index).show();
setTimeout(hideDiv, delay);
}
function hideDiv(){
divs.eq(index).hide();
setTimeout(showNextDiv, delay);
}
.someClass{ display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="someClass">1</div>
<div class="someClass">2</div>
<div class="someClass">3</div>
<div class="someClass">4</div>

I have the JS function that is invoked every 3 minutes by setInterval - how can I invoke it when page loads too?

I have the following script:
var results;
var cursor = 0;
function myFunction () {
$.getJSON('list.php', function(json) {
results = json.result;
cursor = 0;
// Now start printing
printNext();
});
}
function printNext(){
if(cursor == results.length){
// Reset the cursor back to the beginning.
cursor = 0;
}
// Print the key1 in the div.
//$('#device-content-user-text').html(results[cursor].key1);
$('#device-content-user-text').hide('fast', function(){ $('#device-content-user-text').html(results[cursor].key1); $('#device-content-user-text').show('fast'); });
// Set a delay for the current item to stay
// Delay is key2 * 1000 seconds
setTimeout(function(){
printNext();
}, results[cursor].key2 * 1000);
// Advance the cursor.
cursor++;
}
var interval = setInterval(function () {
myFunction();
}, 300000); //make sql query every 5 minutes
and it gets the JSON string from the page list.php and prints the results one by one in a #device-content-user-text div. It is done every five minutes and the timer starts counting time when the user loads the page. How can I invoke this function also on the page load (and then normally every 5 minutes)?
Thanks
Use document.ready() like
$(document).ready(function(){
var interval = setInterval(function () {
myFunction();
}, 300000); //make sql query every 5 minutes
myFunction();
});
Also, if your just calling myFunction inside the anonymous function of setInterval, just pass the function reference itself
$(document).ready(function() {
var interval = setInterval(myFunction, 300000); //make sql query every 5 minutes
myFunction();
});
Update
Depending on what you meant by page 'load', there can be a world of difference between document.ready and load(). If you want to be absolutely sure everything is loaded(including frames, images, etc..) then do
$(window).load(function() {
var interval = setInterval(myFunction, 300000);
myFunction();
});
Otherwise, if it is sufficient that the DOM is ready, just stick with document.ready()
See jQuery - What are differences between $(document).ready and $(window).load?
//Document ready
$(function(){
//call function
myFunction();
//put your interval here
});

Categories