Delaying While Loop in JavaScript - javascript

<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>

Related

SetTimout not properly functioning

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>

Show elements of array one by one - Jquery

So I have a button on which I want to display each element of my array for a few seconds. This is my html code:
<button class="btn" id="random">Start</button>
I have made an array with jQuery that I want to use to change the buttons text:
$(document).ready(function() {
$("#random").on("click", loop);
});
var array = ["el1","el2","el3"];
function loop() {
for (i = 0; i < array.length; i++) {
$("#random").html(array[i]);
}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}
The for loop is supposed to do what I want but I can't find a way to delay the speed, it always just shows the last line of code. When I try setTimeout or something it just looks like it skips the for loop.
My proposal is to use IIFE and delay:
var array = ["el1","el2","el3", "Start"];
function loop(){
for (i = 0; i < array.length; i++){
(function(i) {
$("#random").delay(1000).queue(function () {
$(this).html(array[i]);
$(this).dequeue();
});
})(i);
}
}
$(function () {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>
Basically, a for loop will not help you. It runs with the max speed it can. And delaying it would do no good in js (you would just freeze the browser). Instead, you can just make a function that will execute itself with a delay. Kinda recursion, but not entirely. Below would make the trick.
https://jsfiddle.net/7dryshay/
$(document).ready(function() {
$("#random").on("click", function (event) {
// texts to cycle
var arr = ["el1","el2","el3"];
// get the button elem (we need it in this scope)
var $el = $(event.target);
// iteation function (kinda recursive)
var iter = function () {
// no more stuff to display
if (arr.length === 0) return;
// get top of the array and set it on button
$el.text(arr.shift());
// proceed to next iteration
setTimeout(iter, 500);
}
// start first iteration
iter();
});
});
Use setInterval() and clearInterval()
$(document).ready(
function() {
$("#random").on("click", loop);
}
);
var array = ["el1", "el2", "el3"];
var int;
function loop() {
var i = 0; // variable for array index
int && clearInterval(int); // clear any previous interval
int = setInterval(function() { //store interval reference for clearing
if (i == array.length) clearInterval(int); // clear interval if reached the last index
$("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>
UPDATE : If you need to implement it using for loop and setTimeout() then do something like this
var array = ["el1", "el2", "el3", "Start"];
function loop() {
for (i = 0; i < array.length; i++) {
(function(i) {
setTimeout(function() {
$("#random").html(array[i]);
}, i * 1000);
})(i);
}
}
$(function() {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>

setInterval doesnt tigger inner script on first time run

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

Javascript SetTimeout chaining

This may be a simple problem but I can't seem to embed a variable parameter in a function for future execution. "alert" is the function I'd like to delay execution, with the parameter 0, 1, 2 etc
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var then;
then = (function(jj) {
return jj;
}(i));
var pp = function(jj) {
return alert(then);
};
setTimeout(function() {
pp();
}, then * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
You didn't really ask a question so I'll assume any implementation that produces the results you were expecting is what you want.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
function createfunc(i) {
return function() { alert(i); };
}
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var func = createfunc(i);
setTimeout(func, i * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
This will alert a number, then wait a second and alert another number. Until 3 is reached:
var init = function() {
var counter = 0, //Start
max = 3 //End
var count = function() {
alert(counter) //Alert
if ( counter < max ) { //If we havent reached 3 then queue this function to be called again
window.setTimeout(function() {
count()
}, 1000)
}
counter++
}
count() //Start the counter
}
Here is a fiddle: http://jsfiddle.net/EXwH2/1/
You enclosed the first function in a closure but not the second, so you essentially set your pp var to the last iteration before setTimeout is called for the first time. What's your intent with the then variable? If you want to stagger the calls, each with their own value, you might want to put the call to setTimeout itself within its own closure:
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
(function (jj) {
setTimeout(function() {
alert(jj);
}, jj * 1000);
})(i);
}
};

how to replace a value in a division for every 5 seconds in jquery?

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.

Categories