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>
Related
So from what I have understood, setInterval() is used to call a function on repeat on regular intervals.
So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever.
What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
Your code is executing the setInterval thrice in the while loop, which is not needed.
Actually, setInterval does not work as a function call but actually registers a function to be called at some interval.
The setInterval() method will continue calling the function until clearInterval() i.e it is deregistered or the process is killed.
It should work like this
var i = 3;
var interval = setInterval(message, 1000);
function message() {
if (i === 0) {
clearInterval(interval);
}
console.log("hey");
i = i - 1;
}
To clear a setInterval, use global clearInterval method.
Example:
var timerId = setInterval(func, 500);
.... some code here....
clearInterval(timerId);
What can I do to stop it after a set number of times.
usually you don't use setInterval() for this, you use setTimeout().
Something like
var counter = 0;
function message() {
console.log("hey");
// we trigger the function again after a second, if not already done 3 times
if (counter < 3) {
setTimeout(message, 1000);
}
counter++;
}
// initial startup after a second, could be faster too
setTimeout(message, 1000);
The setInterval function calls the function indefinitely, whereas setTimeout calls the function once only.
Simply use clearInterval once the count runs out.
var i = 3;
function message(){
console.log("hey");
if (--i < 0) {
clearInterval(tmr);
}
}
var tmr = setInterval(message, 1000);
you have to assign that setInterval to a javascript variable to name it what for this setInterval, like this
var messageLog = setInterval(message, 1000);
After, in setInterval message function add this condition to clear the inverval whenever you want to clear.
function message(){
if(i>3) {
clearInterval(messageLog); // clearInterval is a javascript function to clear Intervals.
return null;
}
console.log("hey");
}
You can retrieve the timer when creating and clear it if needed.
var i=3;
var timer = setInterval(message,1000);
function message(){
console.log("hey");
i—-;
if(i==0)
clearInterval(timer)
}
a beginner here too,look for clearInterval method ...
guys. It's a timer. I wanna run the timer and when it's end do something else(like a warning),and then run again with other amount of minutes. But I can't cause always only the second call is executed:
$(document).ready(function() {
timer(5,timer(25));
// timer(5);
// timer(25); do not work... only exec de last one
});
function timer(countTo,callback){
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset-(i*(initialOffset/countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
i++;
}, 1000);
callback();
}
Which is the best solution? There is something that I am not understanding... Thanks anyway!
Well, first off:
timer(5,timer(25));
If you think this line will execute timer(5), and then at the end of timer(5) it will execute timer(25), you are mistaken. This is actually going to evaluate timer(25) immediately, and pass its return value (undefined) as the second parameter to timer(5,undefined).
If you intended to pass that as a callback, you need to pass a function. So you could do:
timer(5,timer.bind(null,25));
But, for that matter, you don't even check if callback exists before attempting to invoke it, so you probably are getting a reference error anyway.
timer(5,timer(25));
starts two timers and passes the result of the second (undefined) to the first as callback. You want:
timer(5,timer.bind(window,25));
And the callback needs to be executed if i==countTo ...
Is this what you want?
timer(5,function(){timer(25)});
Your problem is here:
timer(5,timer(25));
You should type
timer(5, function(){
timer(25)
});
//or using ES6 syntax
timer(5, () => timer(25));
because timer(25) returns its value (this function doesn't return value so it tries to invoke undefined), not that function.
Also read about closures, it might be helpful.
Instead of runing a callback(), you need to run the function itself (timer()). You'll also need to run a for loop inside your function that checks how many times the function has already run. If it reaches your desired maximum, break out of that. This way it won't run indefinitely.
In the following example, the timer() function executes five times, which is what I'm assuming you want by calling timer(5).
$(document).ready(function() {
timer(5);
});
function timer(countTo) {
for (var iterations = 0; iterations < countTo; iterations++) {
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset - (i * (initialOffset / countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
}, 1000);
timer();
console.log("Iteration:", iterations + 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To run the function 25 times after this, all you have to do is call timer(25) directly after timer(5):
$(document).ready(function() {
timer(5);
timer(25);
});
$(document).ready(function() {
timer(5);
timer(25);
});
function timer(countTo) {
for (var iterations = 0; iterations < countTo; iterations++) {
var time = 10; /* how long the timer runs for */
var initialOffset = '440';
var i = 1
var interval = setInterval(function() {
$('.circle_animation').css('stroke-dashoffset', initialOffset - (i * (initialOffset / countTo)));
$('h2').text(i);
if (i == countTo) {
clearInterval(interval);
}
}, 1000);
timer();
console.log("Iteration:", iterations + 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this helps! :)
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)
};
I want to terminate the interval created with setInterval if the count goes to 3.
I tried the code below but it is not calling the alert inside the if block. Why? Is my comparison not correct or is something else wrong?
$(window).load(function() {
var timerId = 1;
timerId = window.setInterval(function() {
timerId = timerId + 1;
if(timerId == '3') {
alert(timerId);
clearInterval(timerId);
}
}, 2000);
});
Try not using the same variable for everything
$(window).load(function() {
var timerNum = 1,
timerId = window.setInterval(function(){
timerNum++;
if( timerNum == 3 ){
clearInterval(timerId);
}
}, 2000);
});
You can't use the same variable for the count and the interval, the count is something you update yourself adding 1 every time the callback in the interval executes, while the setInterval function returns a unique ID that can later be passed to clearInterval to clear that specific interval, and by overwriting that ID with your number the unique ID is lost, and the interval can no longer be cleared.
$(window).load(function() {
var timerId =1;
timerCount = window.setInterval(function(){
timerId=timerId+1;
if(timerId=='3'){ alert(timerId); clearInterval(timerCount);}
}, 2000); });
You have two variables with the same name, change one of the variables names to avoid them 'clashing'.
You are using same variable for storing an integer value and unique interval ID return by window.setInterval. So use different variables , that may fix your problem
$(window).load(function() {
var timerId =1;
var intId = window.setInterval(function(){
timerId=timerId+1;
if(timerId=='3'){ alert(timerId); clearInterval(intId);}
}, 2000); });
I have a setInterval function like below on a Divbox so if I leave a divbox, this setInterval is triggered:
setInterval("playthis()", 1000);
What I want it to do: If I leave the divbox and lets say within the next 2 second rehover it, the setInterval should not triggered.
Is this possible?
You can use cousins setTimeout and clearTimeout to set a function callback that invokes your setInterval only after 2 uninterrupted seconds:
var handle = null;
function yourDivboxLeaveHandler() {
handle = setTimeout(startPlay, 2000);
}
function yourDivboxHoverHandler() {
if (handle !== null) {
clearTimeout(handle);
handle = null;
}
}
function startPlay() {
setInterval(playthis, 1000); // use function references please, not eval
handle = null;
}
You will want much better variable/function names than this though.
Yes. Just make some creative use of clearInterval().
In other words, no, such a feature doesn't come out-of-the-box, but you can build it yourself by calling clearInterval() if the mouse re-enters the divbox before the interval is triggered.
For example:
var divBox = document.getElementById('MyDivBox');
var TimeoutHandle = null;
divBox.onmouseover = function()
{
if ( TimeoutHandle != null )
{
clearTimeout(TimeoutHandle);
}
}
divBox.onmouseout = function()
{
TimeoutHandle = setTimeout(function()
{
TimeoutHandle = null;
setInterval(playthis, 1000);
}, 2000);
}
First of all is a bad practice to have the code evalued in a setInterval so you should avid double quotes. Then you can clear the interval like this:
var int = setInterval(playthis, 1000);
clearInterval(int)