I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...
$(document).ready(function(){
$("#start").click(function(){
for(var i = 0; i < 5; i++){
setTimeout(function(){
console.log("hello world")
},5000)
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?
You can use a for loop, but you need to give different timeouts so they'll run at different times.
$(document).ready(function(){
$("#start").click(function(){
for(var i = 0; i < 5; i++){
setTimeout(function(){
alert("hello world")
}, 5000 * (i + 1))
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
Please check below mentioned solution.
var i = 1;
var interval = setInterval(
function(){
if(i<=5){
alert('Hello World!');
i++;
}else{
clearInterval(interval);
}
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Let me know if it not works
I've updated the answer using setInterval and instead of for loop you can pass data runTimer method
function runTimer(callback, delay, repeat) {
var i = 0;
var timer = setInterval(function () {
callback();
i++;
if (i == repeat) clearInterval(timer);
}, delay);
}
$(document).ready(function(){
$("#start").click(function(){
runTimer(function(){
alert('hello')
}, 5000, 5);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
Related
<html>
<body>
Click Here
<body>
</html>
I am using the following code to check the href attribute of the anchor tag and if it is blank I want to show alert for now. But when I write the code of javaScript in web browser console my complete system ends up unresponsive for quite some time. I might be doing something wrong. Can someone explain me what?
var a = document.getElementById("content2").getAttribute("href");
let i = 0;
while(a.trim().length < 1)
{
task(i);
}
function task(i) {
setTimeout(function() {
alert(i);
}, 1000 * 10);
}
Your timeout call seems to be within a while loop which gets called a ton of times. It should be
var a = document.getElementById("content2").getAttribute("href");
let i = 0;
if (a.trim().length < 1) {
task(i);
}
function task(i) {
setTimeout(function() {
alert(i);
if (a.trim().length < 1) {
task(++i);
}
}, 1000 * 10);
}
<html>
<body>
Click Here
</body>
</html>
This runs your loop after each attempt where a.trim().length < 1
You need change while loop to if condition, the while loop have never ended.
var a = document.getElementById("content2").getAttribute("href");
let i = 0;
if(a.trim().length < 1)
{
task(i);
}
function task(i) {
setTimeout(function() {
alert(i);
}, 1000 * 10);
}
<html>
<body>
Click Here
<body>
</html>
I am running the JavaScript timer using setInterval(). I want to run the timer for 5 seconds then restart the timer from zero seconds and the same process should run for 3 times.
<!DOCTYPE html>
<html>
<head>
<title>Jquery setinterval stop after sometime</title>
</head>
<body>
<p>Counter: <span id="counter"></span></p>
<p>Seconds: <span id="seconds"></span></p>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var start_secs;
var counter = 0;
function intervalFunc(){
var seconds = 0;
$('#counter').html(counter);
start_secs = setInterval(function(){
$('#seconds').html(seconds);
if(seconds===5){
if(counter < 3){
intervalFunc();
}else{
console.log('else');
clearInterval(start_secs);
seconds=0;
return false;
}
}
seconds++;
}, 1000);
counter++;
}
intervalFunc();
});
</script>
</body>
The above code timer works fine until counter value is less than 3 but after that setInterval() keeps running and doesn't stop even on using clearInterval().
Can anyone point out the problem in the given code that why setInterval() is not stopping after counter value is greater than or equal to 3 ?
There are a few problems. The main one is that start_seconds needs to be local to the function rather than declared outside the function — you want to control each interval independently within the function. The way you have it, you lose the references to the earlier timers. And you want to clear the interval when seconds == 5 regardless of whether the counter < 3 because you are starting a new one.
Something like this:
var counter = 0;
function intervalFunc(){
var seconds = 0
var start_secs = setInterval(function(){
console.log(seconds)
if(seconds===5){
if(counter < 3){
intervalFunc();
}
// after 5 times clear the interval
// a new one is started if counter < 3
clearInterval(start_secs);
return
}
seconds++;
}, 500);
counter++;
}
intervalFunc();
Before calling the intervalFunc() you must clear your previous timer. Because every timer is assigned to the same variable, so the timer is running in the background and then there is no way to clear those timers.
Check the code with the changes:
<!DOCTYPE html>
<html>
<head>
<title>Jquery setinterval stop after sometime</title>
</head>
<body>
<p>Counter: <span id="counter"></span></p>
<p>Seconds: <span id="seconds"></span></p>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var start_secs;
var counter = 0;
function intervalFunc(){
var seconds = 0;
$('#counter').html(counter);
start_secs = setInterval(function(){
$('#seconds').html(seconds);
if(seconds===5){
clearInterval(start_secs);
if(counter < 3){
intervalFunc();
}else{
console.log('else');
seconds=0;
return false;
}
}
seconds++;
}, 1000);
counter++;
}
intervalFunc();
});
</script>
</body>
you only need to call setInterval once because it will continue running before you stop it.
$(document).ready(function() {
var start_secs;
var counter = 0;
var seconds = 0;
function intervalFunc() {
if (seconds === 5) {
seconds = 0;
counter++;
if (counter == 3) {
// seconds = 5; // uncomment to show 5 instead of 0 when finished
clearInterval(start_secs);
console.log('Finish');
}
}
else {
seconds++;
}
$('#seconds').html(seconds);
$('#counter').html(counter);
}
start_secs = setInterval(intervalFunc, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Counter: <span id="counter">0</span></p>
<p>Seconds: <span id="seconds">0</span></p>
As you may know now after the previous answers, you are calling setInterval many times thus creating many intervals that are impossible to clear.
When you are calling the intervalFunc again inside it, it goes through the setInterval line and sets another Interval. Thus creating many intervals until the counter reaches 5 and clears ONLY ONE interval after the conditioning fails. Here is a tested code that can do it without any issues:
$(document).ready(function() {
var start_secs;
var counter = 0;
var seconds = 0;
$('#counter').html(counter);
$('#seconds').html(seconds);
function increaseCounter(){
counter+=1;
$('#counter').html(counter);
}
var start_secs = setInterval(function(){
if(seconds==5){
seconds=0;
if(counter < 3){
increaseCounter();
}
else if(counter==3){
counter=0;
seconds=0;
$('#counter').html(counter);
$('#seconds').html(seconds);
clearInterval(start_secs);
}
}
$('#seconds').html(seconds);
seconds+=1;
}, 1000);
});
Tested it and it's working. I hope it works for you...
I have an span element. When hovering it, I expected it to change to hello1 -> hello2 -> hello3 every 1 second, but it is not working like that, why?
i = 0;
$('div').on('mouseenter', function() {
interval = setInterval(function() {
$('div').html('<span>hello' + i +'</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span></div>
Your i is incremented outside the setInterval meaning it will only increment on mouseenter. You should also clear the interval each time you mouseenter to avoid lots of intervals going at the same time
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/
Alternatively if you want the code to only increment on hover and to reset when you stop hovering use the following
i = 1;
var interval;
$('div').hover(function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
},
function() {
clearInterval(interval);
i = 1;
$('div').html('<span>hello</span>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/1/
I think you want to use .append() instead of .html()
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').append('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
Here's a simple version with pure JavaScript!
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>Hello 0</span>
<script>
var innerNumber = 0; // The number that will increments.
var span = document.querySelector('span'); // Adding some reference to the element and event handlers.
span.addEventListener('mouseover', setInterval(changeText, 1000));
function changeText(){
span.innerHTML = 'Hello ' + (innerNumber + 1); // Obtaining the content of the element and adding 1.
innerNumber = innerNumber + 1;
}
</script>
</body>
</html>
Maybe I'm not properly understanding setInterval but I have made a kind of slideshow script, as below:
var i = 0;
setInterval(function() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
if(i == 5){
i = 0;
}
}, 4000);
This works, except for the first run - no slides will display for the first 4 seconds.
See Fiddle here: http://jsfiddle.net/vpa89snf/6/
Is there anyway I can trigger whats inside the setInterval function when it runs the first time round?
Use setTimeOut instead of setInterval for better performance, inspect the sample below:
Here is working jsFiddle.
var i = -1;
var totalSlide = $('.slide').length-1;
var slideTimer = 0;
function nextFrame() {
i == totalSlide ? i = -1 : i;
i++;
$('.slide').fadeOut(200);
$('.slide').eq(i).fadeIn(200);
slideTimer = setTimeout(nextFrame,4000);
}
$('#holder').addClass('isAni');
nextFrame();
// play / pause animation
$('#holder').click(function() {
if ( $(this).hasClass('isAni') ) {
$(this).removeClass('isAni');
clearTimeout(slideTimer);
}else{
$(this).addClass('isAni');
nextFrame();
}
});
You need to run the function and not wait for the 4 first seconds:
var i = 0;
function doSomething() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i = (i + 1) % 5;
}
$document.ready(function () {
setInterval(doSomething, 4000);
doSomething(); // run it!
});
JSFIDDLE.
This is how setInterval is executed. It runs your function after x milliseconds set as 2nd parameter.
What you have to do in order to show the first slide is to have the 1rst slide fadein like below:
var i = 0;
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
setInterval(function() {
...
}, 4000);
I want to replace a value in a div with id show_num_val with new value for every 5 seconds. For that I have written the following.
<div id="show_num_val"> 0 </div>
In the script:
<script>
$(document).ready(function() {
for(i=0;i<20;i++){
showThis(i);
}
});
function showThis(x) {
setTimeout(function() {
$('#show_num_val').html(x);
}, 5000);
}
</script>
But I am getting the last value i.e 20 only in the show_num_val div.
can anybody help?
You can use setInterval() if you want repetitive execution.
Live Demo
$(document).ready(function() {
x = 1;
inverval = setInterval(function() {
$('#show_num_val').html(x++);
if(x == 21)
clearInterval(inverval);
}, 2000);
});
var x = 0;
T = setInterval(function() {
if (x == 20) clearInterval(T);
$('#show_num_val').html(x);
x++;
}, 5000);
See it working http://jsbin.com/ajekeq/2/watch
<script>
$(document).ready(function() {
for(i=1; i<20; i++){
showThis(i, 5000 * i));
}
});
function showThis(x, y) {
setTimeout(function() {
$('#show_num_val').html(x);
}, y);
}
</script>
The reason why your code was not working because all the timers were getting over at the same time. I would have liked to use setInterval though as we are starting 20 timers at the same time. Another model is to start next timer in the setTimeout call till you are done.