JavaScript Calling Function2 after Function1 has ended - javascript

I have already searched for the problem and found something in here about it, but iam not able to use it in my programm, eventually i havent understood it completly.
var header = "welcome";
var text = "hello";
var headlength = 0;
var textlength = 0;
function do_header(lightup)
{
if (headlength <=header.length)
{
if(headlength !==header.length)
window.document.getElementById('header').innerHTML=header.substr(0, lenghtheader++)+"_";
else
window.document.getElementById('header').innerHTML=header.substr (0, lenghtheader++);
if(lightup)
window.setTimeout ("do_header(1)", speed);
else
window.setTimeout ("do_header(0)", speed);
}else{
do_text(); }
}
function do_text()
{
if (textlength <=text.length)
{
if(textlength !==text.length)
window.document.getElementById('text').innerHTML=text.substr (0, lenghttext++)+"_";
else
window.document.getElementById('text').innerHTML=text.substr (0, lenghttext++);
window.setTimeout ("do_text()", speed);
}
else
{
.... eventually start 3. function
}
}
thanks for any help .

Try this approach. using callback
function do_header(lightup,callback) {
//your code
callback();
}
function do_text(){
//your code
}
//now call
do_header(lightup,do_text);

Related

Javascript: how to set intervals with a variable or run code once?

I have a problem with javascript because I want to run code in a function once until a interval is again over. So I have read about a possibilty to use an boolean to control it but without intervals and it is still calling the updatePosition() function over and over without stopping.
Simplyfied I have code in this structure:
var runPerm = false;
function start() {
setInterval(setPerm, 2000);
setInterval(function() {
new updatePosition()
}, 2000);
}
function setPerm() {
runPerm = true;
}
function updatePosition() {
if (runPerm == true) {
//some code that I want to run once.
runPerm = false;
}
}
Has someone an idea to solve the problem?
(A full code: http://pastebin.com/iSFHjct3 )
Use setTimeout.
var runPerm = false;
function start() {
setInterval(setPerm, 2000);
setTimeout(updatePosition, 2000);
}

Call a function according to the elements of an array

I am a beginner in JavaScript and jQuery, and I would like to have an idea to how to proceed with this part of a code,
I have a function with a callback, for example:
myFunc(elem, callback) {
$(elem).fadeIn(function(){ callback(); });
}
and I want to run this function for elements that are in an array:
elems = ['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'];
but, I want to execute this function for each element of the array, one by one through the callback.
eg. once #elem1 has fadein, it must fadein second element ..etc
now I proceed like this:
I have tried to do a for loop, but they are executed in the same time.
for (i = 0; i < elems.length; i++) {
myFunc(elem[i], function(){
if (elem[i+1]) {
myFunc(elem[i+1]);
}
});
}
So how would you proceed?
Do like this, A recursive solution for your problem,
function myFunc(elems, cnt)
{
if(cnt > (elems.length - 1)) { return; }
$(elems[cnt]).fadeIn("slow", function(){ myFunc(elems , ++cnt); });
}
myFunc(['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'], 0);
DEMO
Update on link:
http://jsfiddle.net/kuw6tt92/1/
function fadeIn(selectors) {
var elements = Array.prototype.slice.call($(selectors));
function fade() {
jQuery(elements.shift()).fadeIn("slow", fade);
}
fade();
}
fadeIn("div");
try
var elems = ['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'];
var len = elems.length;
function myFunc(index) {
$(elems[index]).fadeIn(function () {
if (len > ++index) myFunc(index);
return;
});
}
myFunc(0);
DEMO

window.settimeout in javascript loading too fast

I have this js code that has to make the height of a panel bigger on load of my page. But it seems to be loading it way too fast.
var TimerID;
function LoadDoc() {
for(i=0;i<=100;i++){
TimerID=window.setTimeout(MoveRolldownDown(i),5000);
}
}
function MoveRolldownDown(i){
document.getElementById('Rolldown').style.height=i + '%';
window.clearTimeout(TimerID);
}
This loads in the page nearly instantly, so how can i make this load slower. At the top of my HTML page i have this code
document.onreadystatechange = function () {
if(document.readyState === "complete"){
LoadDoc();
}
}
1st thing -- your functions are executing immediately so you need to put them inside of another function.
One more thing -- all of your timeouts end at basically the same time!
Try something like this:
function LoadDoc() {
for (i = 0; i <= 100; i++) {
var down = i;
setTimeout((function (down) {
return function(){ //return function for timeout
MoveRolldownDown(down);
};
})(i), 10 * i);
}
}
function MoveRolldownDown(i) {
document.getElementById('Rolldown').style.height = i + '%';
}
Demo: http://jsfiddle.net/maniator/RTaZh/
Yes, it because you are calling the function within the parameters,
You probably want something like
window.setTimeout(MoveRolldownDown,5000, [i]);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout

setTimeout keeps firing, how to make it fire only once?

I am making a simple chat, it works in different browsers but setTimeout keeps firing, and I want it to fire only once as it is pointless to keep firing and I believe also it would cause more stress on the server.
This is the function which is called from somewhere else:
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
setTimeout("chat_load();", 1000);
});
}
I tried something like the following but it just keeps on firing. Also, the function is supposed to fire only when a certain button is clicked, which happens only once every so often.
var c = 0;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
c++;
if (c == 3) {
clearTimeout(t);
}
});
}
I think you want something like this:
var c = 0, t;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
clearTimeout(t);
t = setTimeout(chat_load, 1000);
if (++c === 3) {
clearTimeout(t);
c=0;
}
});
}
You can't change variables in a asynchronous function
c++; wont work
maybe you should do this
function addCount() {
c++;
}
and change c++ to addCount();
so this
var c = 0;
function addCount() {
c++;
}
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
addCount();
if (c == 3) {
clearTimeout(t);
}
});
}

Why doesn't the clearInterval() works?

I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}
You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});

Categories

Resources