Problems with setInterval - javascript

I am just trying to implement the most basic example of setInterval with jQuery and am having problems. What's wrong here?
It says function rotate is not defined.
$(document).ready(function() {
var speed = 5000;
var run = setInterval("rotate()", speed);
function rotate() {
alert ('rotate');
}
});

Do this instead:
$(document).ready(function() {
var speed = 5000;
function rotate() {
alert ('rotate');
}
var run = setInterval(rotate, speed);
});
You could also simply do this:
$(function() {
var speed = 5000;
var run = setInterval(function() {
alert ('rotate');
}, speed);
});
You should declare run outside the ready event handler if you wish to be able to clear the interval later though, since it will go out of scope otherwise.

You are passing setInterval a string to eval. This is:
Hard to debug
Inefficient
Ugly
executed in a different scope
The function is limited in scope to the function it is defined inside.
Pass the function directly instead
var run = setInterval(rotate, speed);

omit the parenthesis and quotes around rotate in your setInterval call. You are giving it the function itself, not the name. It shouldn't matter the order that they go in.

That's effectively eval-ing rotate in (what I believe is) its own context. Change it to
var run = setInterval(rotate, speed);
and it should be fine.

or even put the rotate function outside the ready function.

this works
$(document).ready(function() {
function rotate() {
alert ('rotate');
}
var speed = 5000;
var run = setInterval(function() { rotate() }, speed);
});

$(function() {
var speed = 5000;
var rotate = function() {
alert("rotate");
};
window.setInterval(rotate, speed);
});

You need to define rotate in the global scope.
$(document).ready(function() {
window.rotate = function() {
alert ('rotate');
}
var speed = 5000;
var run = setInterval("rotate()", speed);
});

Related

How to stop a function in another function

How i can stop a function in another function?
For example:
var snow = function(){
var interval = setInterval( function(){
alert('letItSnow')
}, 1000);
};
snow();
clearInterval(snow.interval) - exception
In javascript, access scopes are limited via function declarations, so your locally declared variables won't be accessible outside, hence you must return it or set it to a global variable (variable available in parent scope)
you need to make a slight adjustment to your function, do it like this:
var snow = function(){
return setInterval(function(){
alert('letItSnow');
}, 1000);
};
var interval = snow();
//on some event -- clearInterval(interval)
you can also make the setTimeout and its returned id a property to the function which would be available on all of its instances i.e.
var snowClass = function(){
this.init = function(msg){
this.interval = setInterval(function(){alert(msg)},1000);
}
}
var snowObj = new snowClass();
snowObj.init('Let it snow');
//on some event -- clearInterval(snowObj.interval)
you referring to snow.interval which assumed to be property of snow object. but in your code interval is just local variable. instead you might want to define interval in the global scope so it will be accessible globally http://www.w3schools.com/js/js_scope.asp
var interval, snow = function(){
interval = setInterval( function(){
console.log('letItSnow')
}, 1000);
};
snow();
clearInterval(interval);
If I understand the question correctly, you want to stop the interval outside of the snow function.
You can declare the interval variable outside of the snow function in order to use it (to clear the interval) outside of the snow function.
var interval;
var snow = function(){
interval = setInterval(
function(){
alert('letItSnow')
},
1000
);
};
snow();
clearInterval(interval);
try this in your code
var timeout1 = {};
var timeout2 = {};
function function1(){
//codes
if(timeout2){
clearTimeout(timeout2);
}
timeout1 = setTimeout("function1()",5000);
}
function function2(){
//codes
if(timeout1){
clearTimeout(timeout1);
}
timeout2 = setTimeout("function2()",5000);
}

Expire or Time Out never ending loop after X seconds

How can I stop this process after, say, 5 seconds?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeBanner(){
// my change banner code
}
window.onload = function () { setInterval(changeBanner, 100) };
</script>
So currently I am changing the banner every 100 milliseconds. But I'd like it to stop after about 5 seconds.
I thought setTimeout might do the trick;
window.onload = function () { setTimeout(setInterval(changeBanner, 100), 5000) };
But that makes no difference.
I'd like it to stop after about 5 seconds.
store the return value given by setInterval and use it with clearInterval
var timer = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(timer)
}, 5000);
There are also several libraries that implement function wrappers to achieve the same. For example, in underscore.js you could use _.before:
var changeBannerLimited = _.before(50, changeBanner);
var timer = setInterval(changeBannerLimited, 100);
Note that contrary to using clearInterval this will continue to call the changeBannerLimited function forever, however after being called 50 times (10 * 5 seconds) it will no longer pass the call on to changeBanner.
On a side note I chose underscore.js because I know it well and because it provides nicely formated annotated source code so you can easily understand what's really going on behind the scenes.
You could store the return value of setInterval to a variable so that you can later cancel it:
function changeBanner(){
// my change banner code
}
window.onload = function () {
var id=setInterval(changeBanner, 100);
window.setTimeout(function() {
window.clearInterval(id);
},5000);
};
Use clearInterval.
window.onload = function () {
var bannerInterval = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(bannerInterval);
}, 5000);
};
persist setInterval output in variable to be able to call clearInterval;
window.onload = function () {
var job= setInterval(changeBanner, 100) ;
setTimeout(clearInterval(job), 5000)
};

Clearing setinterval not working?

var theintrvl = function() {
setInterval(function () {
somefunction()
}, 3000)
}
the somefunction isn't important - all works just fine, BUT! When I try to clear the interval it doesn't clear. Here's what I tried:
document.getElementById('clearme').addEventListener('click', function() {
clearInterval(theintrvl);
});
I also tried somefunction instead the theintrvl, but nothing!
You don't need to wrap it in a function at first place. Just save the value returned by setInterval function
var theintrvl =
setInterval(function () {
somefunction()
}, 3000);
You need to have
var myinterval = setInterval(function, time)
And then to clear it you would do
clearInterval(myinterval)
You may want to get rid of the outside function though because myinterval wouldn't be accessable from outside theintervl
One more thing, you might consider doing
setInterval(somefunction, 3000)
Instead of calling the function from an anonymous function
Hope this helps!
Try this:
var test = setInterval(somefunction, 3000);
clearInterval(test);

Can anyone explain why this JavaScript wont run

Im not very good wit JS and I just dont get why this wont work!
The code uses jquery to apply the pulsate efect to one of my divs and run forever unless I stop it with another function, but I cannot figure our why my first piece of code wont run!
function animate(var x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate("#mydiv"));
Only way to get it working is for me to do this
function animate(){
// Do pulsate animation
$("#mydiv").effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate);
Note that in the first snippet the code uses variables to be more useful and the second piece has the selectors name hardcoded
Don't use var in your function declaration. Just use:
function animate(x){
Also, you probably want something like this for your first example:
function animate(x){
return function () {
function animateInner() {
$(x).effect("pulsate", { times:4 }, 5000);
setTimeout(animateInner, 10000);
}
animateInner();
};
}
$(document).ready(animate("#mydiv"));
DEMO: http://jsfiddle.net/XHKbC/
Otherwise, the original animate("#mydiv") call executes immediately (and $(x) probably won't find anything since the DOM isn't ready yet). $(document).ready() expects a reference to a function. You called a function instead. But that's all a little overkill. Just use:
$(document).ready(function () {
animate("#mydiv");
});
but you'll have to change your function so the setTimeout passes the value of x as well:
function animate(x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(function () {
animate(x);
}, 10000);
}
DEMO: http://jsfiddle.net/XHKbC/2/
Although it's a little more code/complex, my first example doesn't suffer the problem in my second (having to pass x in the setTimeout) by using a closure.
UPDATE:
Being shown how you are using this code, I'd set it up like this:
function Animater(target) {
var self = this;
var animateTO;
var animateElement = target;
function animate() {
animateElement.effect("pulsate", { times:4 }, 5000);
animateTO = setTimeout(animate, 10000);
}
self.start = function () {
animate();
};
self.stop = function () {
animateElement.finish();
clearTimeout(animateTO);
};
}
And create a new one like:
var mydivAnimater = new Animater($("#mydiv"));
You can then call .start() and .stop() on it, and you create any number of these Animater objects on different elements as you want.
DEMO: http://jsfiddle.net/K7bQC/3/
Your code has two issues:
omit the var:
function animate(x){
modify your event handler:
$(document).ready(function(){
animate("#mydiv");
});
You need to hand over a function reference (either animate or function(){}), not run the code right away which you are doing if you pass animate().
Now to not lose the reference to your x you have to modify the animate call in the timeout too:
setTimeout(function () {
animate(x);
}, 10000);
You dont need to type var when specifying a function parameter.

setInterval() not repeating. Works only 1 time

I'm trying to have a div's left property change by its self - one every second when your hovering over so I made this:
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
var timerID = setInterval(alert(left_num1), 1000);
//var timerID = setInterval(slideleft(left_num1), 1000);
},function(){
clearInterval(timerID);
});
//function slideleft(left_num){
//$('.license_video').css('left', left_num + "%");
//}
In theory you would think it repeat till you move your cursor off which clears the interval. When I hover over it does it one time and never repeats (there are no errors). Then when I hover off it gives a error "Uncaught ReferenceError: timerID is not defined"
setInterval isn't working at all. You aren't passing it a function as the first argument.
You are calling alert immediately and trying to use it's return value as the function to repeat.
var timerID = setInterval(function () { alert(left_num1) }, 1000);
So you've got two different problems here:
// (1) timerID needs to be defined in a scope accessible to both hover callbacks
var timerID = null;
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
// (2) Pass a *function* to setInterval
timerID = setInterval(function () {
alert(left_num1)
}, 1000);
}, function(){
clearInterval(timerID);
timerID = null;
});
When you write
setInterval(alert(left_num1), 1000);
// or
setInterval(slideleft(left_num1), 1000);
you are passing the value returned by calling alert() or slideleft() (respectively) to setInterval. You are not passing the function itself.
You are assigning null to be the function to call. Why? Because you called alert and assigned its return value to the setInterval parameter.
Instead, use an anonymous function:
setInterval(function() {doStuff();},1000);
Very easy ;-) ... i love jquery, no matter a version... u need javascript pure is send pm me is can help.
umavez = 0;
setInterval(function() {
if (umavez == 0) {
for (x=0;x<10;x++) {
$('div.test').append('<div>'+x+'</div>');
}
}
umavez = 1;
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="test">Linha:</div>

Categories

Resources