setInterval won't get out of loop - javascript

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);

Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

Related

Unable to auto refresh content

I tried setinterval and settimeout to callback validate() function,but I don't know why it just won't work. Now I try another type of calling method and still not working. Any fix?
Below is the code:
function validate(){
var code = document.getElementById("BScode").value ;
var msg = "<p>ERROR : Please select the option. </p>";
var error = document.getElementById("valError");
error.innerHTML = ""; //clear error-span
document.getElementById("divResult").innerHTML = ""; //clear resutl-div
** document.getElementById("map_title").innerHTML = "";
document.getElementById("map_canvas").style.display = "none"; **
if( code == "" || code == "none" || code == null ){
error.innerHTML = msg;
}else{
//get result
getETA();
auto_refresh_countdown(seconds);
}
}
/* The whole stupid function to call back refresh validate() which failed :)*/
function auto_refresh_countdown(seconds) {
var time = seconds;
var myTimer = setInterval(function() {
time--;
if(time === 0){
clearInterval(myTimer);
validate();
auto_refresh_countdown(seconds);
}
}, 1000);
}
function getETA() {
var seconds = 5;
var id = document.getElementById("BScode").value;
var url = "http://www.cybertowers.net/jsonp/?a=eta.aspx?bid=";
loadData(url, getETACallback);//real
}
Last line, you've got a function getETACallback that is not defined.
I just tried to run auto_refresh_countdown, it works. validate is only called if seconds is different from 1 though.
Plus you have a typo: uto_refresh_countdown --> auto_refresh_countdown

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>

Javascript Text Slideshow

I am trying to add text into a div using JavaScript and/or jQuery and then have that text change to different text every 10 seconds -- so somewhat like a slideshow of just plain text. Here's my code:
<div id="textslide"><p></p></div>
<script>
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
var counter = 0;
while (true) {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstChild.innerHTML = quotes[counter];
counter++;
setTimeout( // not sure what to put here, 500); // Want to delay loop iteration
}
</script>
HTML:
<div id="textslide"><p></p></div>
JavaScript/jQuery:
var quotes = [
"quote1",
"quote2",
"quote3",
"quote4",
"quote5",
];
var i = 0;
setInterval(function() {
$("#textslide").html(quotes[i]);
if (i == quotes.length) {
i = 0;
}
else {
i++;
}
}, 10 * 1000);
Working demo here
Use a function and call it on body onload
<html>
<head>
<script>
var counter = 0;
function changeText()
{
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
if (counter > 4)
{
counter = 0;
}
document.getElementById("textslide").innerHTML = quotes[counter];
setTimeout(function(){changeText()},10000);
counter ++;
}
</script>
</head>
<body onload="changeText();">
<p id="textslide"></p>
</body>
</html>
Here is a suggestion with plain JS
function loop() {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter];
counter++;
setTimeout(loop, 500);
}
loop();
Demo here
If you want to use jQuery you can use this: $('#textslide p:first').text(quotes[counter]);
Demo here
Instead of while, use:
setInterval(function () {
//do your work here
}, 10000);

Making text disappear letter by letter

I am new to JavaScript and jQuery development and I want to ask what is the most simple way of making html text slowly disappear letter by letter using JavaScript?
Thanks.
Since I got even more curious, I think I created the exact one that you are looking for,
DEMO: http://jsfiddle.net/DbknZ/3/
$(function() {
var $test = $('#test');
var initText = $.trim($test.text()), ptr = 0;
var timer = setInterval(function() {
var ln = $.trim($test.find('.trans').text().length);
if (ln == initText.length) {
$test.empty();
clearInterval(timer);
}
$('#test').html(function() {
return $('<span>').addClass('removeMe')
.html(initText.substring(ptr++ , ptr))
.before($('<span>').addClass('trans').
html(initText.substring(0 , ptr-1)))
.after(initText.substring(ptr));
}).find('span.removeMe').animate({'opacity': 0}, 10);
}, 20);
});
I just got curious and wrote a small thing for you.. which could be a starter..
Basically it is a timer which removes letter by letter.. See below.
DEMO: http://jsfiddle.net/TTv7L/1/
HTML:
<div id="test">
This is a test page to demonstrate text disapper letter by letter
</div>
JS:
$(function () {
var $test = $('#test');
var timer = setInterval( function () {
var ln = $test.text().length;
if (ln == 0) clearInterval(timer);
$('#test').text(function (i, v) {
return v.substring(1);
});
}, 100);
});

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories