setInterval in javascript based on changes made - javascript

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

Related

retain differents setInterval with a cookie or localstorage?

I have an automatic mouse with a time interval when I go inside a web. But I have a button that increase that speed but of course when I refresh the page or I go to other part of the web the speed is the first one. I tried with a cookie but I don't know how to do it because by default cookies or localstorage works only with names...
// Default speed
$(document).ready(function() {
t = setInterval(clickbutton, 3000);
}
// Button
function aumentar() {
clearTimeout(t);
t = setInterval(clickbutton, 100);
}
I will be really grateful for your help because I'm going crazy.
Thanks a lot!
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
The function is only executed once. If you need to repeat execution, use the setInterval() method.
Use the clearTimeout() method to prevent the function from running.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
HTML local storage; better than cookies.
Create a localStorage name/value pair with localStorage.setItem("name", "value")
Retrieve the value of "name" and insert it into the element with localStorage.getItem("name")
remove item localStorage.removeItem("name")
var t;
function speed(_speed, boo){
if(boo){
return localStorage.getItem("speed") || 3000;
} else {
localStorage.setItem("speed", _speed);
}
}
$(document).ready(function() {
t = setInterval(clickbutton, speed(true));
// Button
function aumentar() {
clearInterval(t);
speed(100);
t = setInterval(clickbutton, 100);
}
});

How can I reset a settimeout

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! ...
// ...
}

Ending a javascript function

I have an html page that links to a js file that has the following function:
function show360Simple( divContainerId, imageUrl )
The function gets called on an on-click:
<area onclick="show360Simple('pContainer5','images/porch1.jpg');">
And I want to know how to end the function with another on-click:
<div id="close-div" onclick="what is the syntax here to end the above function?"></div>
Its probably simple but I'm a novice and haven't been able to work it out yet - any help is greatly appreciated - cheers.
The script linked above is using setTimeout to manage the animation.
To stop, you will need to modify the code a bit and add a stop function.
The simplest approach would be to store off the timeoutId returned from each setTimeout call. Then, in the stop function, call clearTimeout passing in the stored timeoutId.
Without making too many changes:
// Declare a global timeoutId
var timeoutId;
In function show360 change the setTimeout call to:
timeoutId = setTimeout(…);
In function move360 change the setTimeout call to:
timeoutId = setTimeout(…);
Then add a stop360 function:
function stop360() {
clearTimeout(timeoutId);
}
Demo fiddle
This will stop the animation - basically freezing it. If you want to remove the changes made by the script you could change the stop function to something like this:
function stop360(divContainerId) {
clearTimeout(timeoutId);
if(divContainerId) {
var o = document.getElementById(divContainerId);
o.style.backgroundImage = '';
o.style.position = "";
o.innerHTML = "";
}
}
Demo with Clear

Cant get javascript intervals to work

so im a little new to javascript, but im trying to make a progress bar, with some other functionalities, on click of a button. im tring to use the set interval in javascript in order to time the bar, this is my js so far:
//Javascript Document
function progress(){
Var uno = setTimeout("uno()", 3000);
uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
}
From what i have gathered this is how it works, however i am skeptical as it seems i am setting a variable uno but not doing anything with it.... from my background in php, thats not how that works :p any pointers you guys can give me on this? my html is here: http://jsbin.com/apoboh/1/edit
right now, it does nothing, it gives me : Uncaught ReferenceError: progress is not defined
first, you are using setTimeout not setInterval. The former fires the callback once, the latter indefinitely at a set interval.
Second, these methods return a token that you can use to cancel a setInterval, do this instead
function startProgress(){
// only start progress if it isn't running
if (!App.progressToken) { // App is you apps namespace
App.progressToken = setInterval(function(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}, 3000);
}
}
later, when you want to stop:
function stopProgress(){
clearInterval(App.progressToken);`
delete App.progressToken
}
The variable uno simply holds the handle to the timeout that you just set. You can later use it to clear the timeout before it executes if you need to via a call to clearTimeout().
If you don't need to clear the timeout, then there's really no reason to store the handle at all.
function progress(){
function uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
var timeoutFunc = setTimeout(uno, 3000);
}
You pass a function to setTimeout which it will call later, not a string. So this code will define a function uno, and then pass it to setTimeout and delay 3 seconds then call it every 3 seconds after that.
You forgot to put word "function " before uno()

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

Categories

Resources