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

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

Related

content narration in web page, on tab press not going to speak anything if current task(speak anything) not completed

I am using articulate.js(http://www.jqueryscript.net/demo/Lightweight-jQuery-Based-Text-To-Speech-Engine-Articulate-js/) to read content from page and speak it. It is working fine, just not works if it is speaking something and I have press tab then it stops but not reads tab selected content.
some pre-define functions
<script>
function speak(obj) {
$(obj).articulate('speak');
};
function pause() {
$().articulate('pause');
};
function resume() {
$().articulate('resume');
};
function stop() {
$().articulate('stop');
};
</script>
what I have tried
<script>
$(document).ready(function() {
var counter = 0;
setTimeout(function(){
counter +=1;
if (counter == 1){
explode();
}
},1000);
function explode(){
//$('body').articulate('speak'); // Default for play whole content
$('h1').articulate('speak');
}
$('body').keyup(function (e) {
$().articulate('stop');
if (e.which == 9) { // on tab press start speaking selected element
var i=document.activeElement.id;
$('#'+i).articulate('pause').articulate('stop').articulate('speak');
}
else{ // trying to speak what key has been pressed except tab, but not working
var i=document.activeElement.id;
$('#'+i).val().articulate('speak');
}
});
});
</script>
I am also trying to make it audible(to speak keypress) on text box, which is not working
I have make some changes now it is working, but it has certain limitation like it not reads backspace, ctrl, space etc but speak a to z,1 to 0, very well. please improve it
<script>
$(document).ready(function() {
var counter = 0;
setTimeout(function(){
counter +=1;
if (counter == 1){
explode();
}
},1000);
function explode(){
//$('body').articulate('speak'); // Default for play whole content
$('h1').articulate('speak');
}
$('body').keyup(function (e) {
var speaking = $().articulate('isSpeaking');
var paused = $().articulate('isPaused');
// $().articulate('stop');
if (e.which == 9) {
if (speaking) {
$().articulate('pause');
$().articulate('stop');
}
var check =0;
setTimeout(function(){
check +=1;
if (check == 1){
comeback();
}
},1000);
function comeback() {
var i=document.activeElement.id;
$('#'+i).articulate('speak');
}
}
else{
var i=document.activeElement.id;
var m=0;
setTimeout(function () {
m+=1;
if(m==1){
magic();
}
},500);
function magic() {
var tempval=$('#'+i).val();
var lastChar = tempval.substr(tempval.length - 1);
var ht ='<div>'+lastChar+'</div>';
$(ht).articulate('speak');
}
}
});
});
</script>

JavaScript Calling Function2 after Function1 has ended

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

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

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

restart loop after it's paused by flag

I'm putting together some code to essentially replace the contents of a div when I mouseover a specific link. I then added the changer function to cycle through the content replacement automatically. I set flags for mouseover and mouseout and I can actually get the changer function to stop on mouseover but I can't quite figure out how to make it start up again on mouseout. Any advice is appreciated.
var pause=false;
$('.banner-nav a').mouseover(function () {
pause=true;
setFeature(this);
return false;
});
$('.banner-nav a').mouseout(function () {
pause=false;
});
changer(0, 5000);
function setFeature(f) {
var m = $(f).attr('rel');
$('.banner-nav a').not(f).removeClass('active');
$(f).addClass('active');
$('#featureContainer').html($(m).html());
}
function changer(index, interval) {
var buttons = $('.trigger'),
buttons_length = buttons.length;
var button = buttons.eq(index % buttons_length);
setFeature($(button));
setTimeout(function() {
if (!pause) {
changer(++index, interval);
}
}, interval)
}
The issue is that changer is responsible for its own delayed execution, but pausing it stops the scheduled execution. Another problem is that the next scheduled execution (if any) still happens after pausing.
Use setInterval instead of setTimeout. Instead of using a flag, clear the interval to pause and start it again to unpause.
(function() {
var index=0;
function changer() {
var buttons = $('.trigger'),
buttons_length = buttons.length;
var button = buttons.eq(index % buttons_length);
setFeature($(button));
++index;
}
var changerInterval,
period = 5000;
function startChanger() {
if (! changerInterval) {
changerInterval = setInterval(changer, interval);
}
}
function stopChanger() {
clearInterval(changerInterval);
changerInterval = 0;
}
$('.banner-nav a').mouseover(function () {
stopChanger();
setFeature(this);
return false;
});
$('.banner-nav a').mouseout(function () {
startChanger();
});
/* could implement other functions to e.g. change the period */
function setChangerPeriod() {
...
}
window.setChangerPeriod = setChangerPeriod;
...
})

Categories

Resources