How can I reset a settimeout - javascript

I tried the answer here: Resetting a setTimeout, but it doesn't seem to be working for me.
I'm building a catalog viewer using Owl Carousel. I have a function set to go off on the afterMove event handler that shows what page the user is on. It displays the page counter and then sets a timeout to have it fadeout after 1 second. Probably is lots of people go through pages faster than once per second. So, I need to reset the timeout if the function gets called again.
function showCounter(){
var $counter = $('#counter');
//clear timeout
window.clearTimeout(timeout);
//Display counter
$counter.show();
//set timeout
var timeout = window.setTimeout(function(){
$counter.fadeOut(500);
}, 1000);
}
But window.clearTimeout(timeout) doesn't seem to be working and I'm not sure why
Thanks

var timeout inside the function makes timeout local to the function; thus, every time you call showCounter, timeout is undefined. Move the variable declaration out of the function:
var timeout;
function showCounter() {
// ...
timeout = // NO VAR! ...
// ...
}

Related

clearInterval does not reset the setinterval value

I'm making a slot machine simulator to learn javascript and messing around with setInterval() and clearInterval(). To simulate the slow stopping of the rows I set asetTimeout() to clear the Intervals of my 3 columns, but the timer doesn't reset the function is still called, I also tried a console log inside the setTimeout and the calls are correct 1sec after 2sec another log and then the third. what I'm doing wrong?
Here try the game and the full code with HTML: https://jsfiddle.net/orphtv1m/1/
//Here i initialize my setInterval
wheelIntervals[i] = setInterval(function(){
columns[i][numberStart[i]].style.background = "white";
numberStart[i] = (numberStart[i]+1)<10 ? numberStart[i]+1 : 0;
columns[i][numberStart[i]].style.background = "red";
},timer);
/*Code*/
setTimeout(function(){
//Here i try to clear it
console.log('Helo');
clearInterval(wheelIntervals[i]);
},i*1000);
}
setTimeout(endGame(), 3000);
}); ```
clearInterval(wheelInterval[i])
Will be always called with i equal to 2
Using setTimeout inside loops might be a little bit tricky because of closures.
Here is an explanation how to do it correctly: https://medium.com/#axionoso/watch-out-when-using-settimeout-in-for-loop-js-75a047e27a5f

Javascript time counter for calling ajax

I have a number of different form elements. When any of the form elements have their value changed, I need to make an ajax call 500ms after the change.
However, should another form element have its value changed then I would like to reset the timer to 500ms, thus avoiding multiple Ajax requests for a series of changes that happen within 500ms of each other.
Is there a JavaScript or jQuery solution to this requirement?
Here's some code that demonstrates the principles you're looking for:
// Keeps track of the timer id in a scope that is outside of the event function
// The variable will remain in memory and available to the next event call
var myTimer;
// Detect changes on keyup.
$('.textbox').on('keyup', function () {
console.log('keyup');
setMyTimer(500);
});
// Detect on change.
$('select').on('change', function () {
console.log('change');
setMyTimer(1000);
});
function setMyTimer(timerDelay) {
// if myTimer has a value, then we should clear the timer. This stops us
// from queuing multiple timers
if (myTimer) {
console.log('clear tiemout');
clearTimeout(myTimer);
}
// Set the timer. It will be cleared if there is another handled 'keyup'
// event sooner than the timerDelay parameter
myTimer = setTimeout(function () {
console.log('Ajax stuff');
// ajax stuff
}, timerDelay);
};
Remove the console.log code before using in production.
See this working demonstration:
http://jsfiddle.net/cC6Dq/5/

setInterval in javascript based on changes made

I'm having an issue with a javascript requirement. I have a html calling a script perpetually every 1500ms using setInterval.
var t = setInterval(loadData(),1500);
The loadData function calls a script which returns a JSON as a list, what I want to do is to change from a fixed interval to a variable interval. For instance, if there are no changes made between two calls to the script, I must set another value for the interval. I heard I could use jquery linq to compare the length of the list at the beginning and the list when refreshing to change the time value. I also heard I could save the value of count in a cookie to compare always.
Any idea please? I would be grateful. Thanks in advance.
I'm guessing you're trying to do:
var speed = 1500,
t = setInterval(loadData, speed);
function loadData() {
if (something == true) {
something = false;
speed = 3000;
clearInterval(t);
t = setInterval(loadData, speed);
}else{
//do something
}
}
You should just reference the function, adding the parenthesis runs the function immediately. When using a variable for the speed, you'll need to clear and run the interval function again to change the speed.
if the interval is variable, then you can't use setInterval, which period won't be changed after the first call. You can use setTimeout to alter the period:
var period=1500
var timer;
var callback = function() {
loadData();
timer = setTimeout( callback, period )
};
var changePeriod = function( newPeriod ) {
period = newPeriod;
}
//first call
callback();
now, you just need to call changePeriod( ms ) to change the period afterwards

Stopping a running function in javascript/jquery on click event

I have a slideshow function in jquery that I want to stop on a particular click event. The slideshow function is here:
function slider(){
setInterval(function(){
var cur = $('img.active');
cur.fadeOut('fast');
cur.removeClass('active');
cur.css('opacity','0');
cur.addClass("hidden");
var nextimg;
if (!cur.hasClass("last")){
nextimg = cur.next("img");
}
else {
nextimg = cur.prev().prev().prev();
}
nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
},5000);
}
I have been reading about .queue but not sure how I can use it exactly, can I call my function from a queue and then clear the queue on a click event? I cannot seem to figure out the syntax for getting it to work of if thats even possible. Any advice on this or another method to stop a running function on a click would be appreciated.
For what it's worth, it's generally advisable to use a recursive setTimeout instead of a setInterval. I made that change, as well as a few little syntax tweaks. But this is a basic implementation of what I think you want.
// Store a reference that will point to your timeout
var timer;
function slider(){
timer = setTimeout(function(){
var cur = $('img.active')
.fadeOut('fast')
.removeClass('active')
.css('opacity','0')
.addClass('hidden'),
nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
nextimg.removeClass('hidden')
.fadeIn('slow')
.css('opacity','1')
.addClass('active');
// Call the slider function again
slider();
},5000);
}
$('#someElement').click(function(){
// Clear the timeout
clearTimeout(timer);
});
Store the result of setInterval in a variable.
Then use clearInterval to stop it.
Store the value returned by setInterval, say intervalId to clear it, your click handler should look like this:
function stopSlider() {
//prevent changing image each 5s
clearInterval(intervalId);
//stop fading the current image
$('img.active').stop(true, true);
}

how to reload javascript code block

I need to reload a block of javascript every amount of time.. say
<script type="text/javascript">
var frame = some sort of code;
</script>
i need that block of any function to be reloaded every 15 seconds without reloading the page itself .. something like jQuery time out but i don't know how to apply it..
any idea?
var frame;
setInterval(function() {
frame = someSortOf.Code();
}, 15000);
That will execute the provided function every 15 seconds, setting your value. Note the var frame is declared outside the function, which gives it global scope and allows it to persist after your function executes.
You should not really "reload" a script. What you really want to do is simply run an already loaded script on a set interval.
function foo() {
// do something here
if (needRepeat) {
setTimeout(foo, 15000);
}
}
setTimeout(foo, 15000);
You can use setTimeout('function()', 15000); - put this line of code at the end of the function() so that it calls itself again after 15000ms.
The other way is just to call setInterval('function()', 15000); and this will call your function() every 15000ms.
The difference between the first and the second one is that the first calls the function after specific milliseconds (only once, so you need to insert it in the function itself) and the second one just calls the function every n milliseconds.

Categories

Resources