setTimeout function in jQuery not working [duplicate] - javascript

This question already has answers here:
'setInterval' vs 'setTimeout' [duplicate]
(5 answers)
Closed 1 year ago.
I am trying to use set time function if a class exists in the document and that class has some specific data-attributes.So I have started to code in the very generic way and also tried all the ways even using setTimeout in the function, but not working...
Here is the code
jQuery(document).ready(function(jQuery){
if( jQuery('.conversion-content').length > 0 ){
var thread_id = jQuery('.conversion-content').attr('data-thread-id');
var sender = jQuery('.conversion-content').attr('data-sender');
setTimeout(function(){
updateConversation(thread_id, sender);
}, 2000);
}
function updateConversation( thread_id, sender ){
console.log(thread_id,sender);
}
});
Its working for the first time but not working from 2nd time, I had pulled out setTImeout function out of the element checking but no work.

First of all you should assign your thread_id and sender inside the timer, so it would change in time.
Second thing... it does shoot only once, because you are not using setInterval(), but setTimeout(). Only the first one is repeating in time, the second one delays the execution (once).
Third thing is that if at start if( jQuery('.conversion-content').length > 0 ){ won't be met, the timer won't even get initialized. So you should put this inside the timer as well.

Related

Didn't updating class for element - jQuery [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 years ago.
After blur, if input is empty, i want to add class .hass-error, after that i write some text into input, on idea class .hass-error must removed and added class has-success. .has-error is removing but new clas
function checkSignupData() {
var username = $('.signup-panel input[name="username"]');
username.on({
'focusin': function(){},
'focusout': function(){
if(!this.value.length) {
$(this).closest('.form-group').removeClass('has-success').toggleClass('has-error');
}
else if(this.value.length > 3 && this.value.length < 32) {
$(this).closest('.form-group').removeClass('has-error').toggleClass('has-success');
}
}
});
}
setInterval(checkSignupData(), 100);
function checkSignupData() {
var username = $('.signup-panel input[name="username"]');
if (username.text().length > 0) {
username.closest('.form-group').removeClass().addClass('has-success');
} else {
username.closest('.form-group').removeClass().addClass('has-error');
}
}
window.setInterval(function(){
checkSignupData();
}, 5000);
This is not an ideal solution using setInterval as the DOM will become messy and slow your application. For example, if this username is within a form, then you can call the check when the form is submitted. Like I said, not the most ideal solution but the one I think you are trying to achieve.
checkSignupData() will be called every 5 seconds.
Another solution I have just thought of which may work:
username.on('keyup', function() {
// call function
});
I originally thought this may not work as it would not fire if nothing was in the input. However, pressing a backspace to remove text will trigger the event as well. The only think is that on start up, you will have to initialise the element to have has-error class as there will be initially nothing in it.
you don't need set interval because you are using events you will end up binding tons of event handlers which is probably causing your problem
also you should use addClass as it's more assertive
edit: remove the setInterval and call checkSignupData one time

setInterval not continuing [duplicate]

This question already has answers here:
JS setInterval executes only once
(2 answers)
Closed 6 years ago.
I can't get this code to do anything beyond counting down to 29 from 30. Does anyone have any insight or hints as to what I am doing wrong to cause it to only run once? I checked to make sure that all the functions are being called with console.logs on game.time (except the clearInterval one since it stops already after the first time through). How do I get the setInterval to keep looping until 0? Thanks in advance for any help! :)
//game object to contain variables and methods
var game = {
// variable for time
time: 30,
// Start button onclick creates the time remaining object and calls the forloop to start
start: function() {
// $("#time").html(game.time);
game.countdown = setInterval(game.count(), 1000);
}, //end of start function
//what the set interval does which is subtract one second from game.time
count: function() {
game.time--;
// if statement to check when time gets to zero
if (game.time <= 0) {
game.stop();
}
// puts the current time left on the page
else {
$("#time").html(game.time);
}
}, // End of count function
// stops the set interval
stop: function() {
clearInterval(game.countdown);
}, // end of stop function
}; // end game object
// Start button click calls the start method
$("#start").click(game.start);
setInterval takes a function refererence as a parameter, it should look like:
setInterval(game.count, 1000)
When you write it as game.count(), you're calling the count() method once, which is evaluated immediately.
Then, setInterval's signature will use the return value from that method instead of a function reference:
setInterval(whatever_the_return_value_was, 1000);
By passing only the reference (as game.count), the timer should work as expected. It will call the reference by itself, every 1000ms.
(MDN docs)

Javascript Function setInterval() works only one time [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
JS setInterval executes only once
(2 answers)
Closed 6 months ago.
Guys!
I wanna ask about Javascript function setInterval().
My problem is that setInterval() works only one time, not repeating.
Here is my HTML Code
<button id = 'btun' name = 'btun' onclick = 'changecolor();' class = 'btn btn-success btn-block'>Color Change</button>
and Javascript Code
function below(t){
var button = document.getElementById('btun');
var quadrant = (t*t + 2*t + 1)+"px";
console.log('ye');
button.style.marginTop = quadrant;
document.write(pix);
}
var doBelow = setInterval(below(t++),1);
if(t > 50){
clearInterval(doBelow);
}
I can't find what is wrong.
setInterval expects a callback as first argument, but you are calling the actual function.
Call should be like below
setInterval(function() {
below(t++); }
,1);
So here you are creating an anonymous callback which will call your function below. And better put the exit condition t >= 50 inside below function
The setInterval doesn't work even one time. The reason that the function is called once is that you are calling it when trying to use setInterval, and the return value from the function (which is undefined) is used in the setInterval call.
Use a function expression to create an interval that calls below(t++). You would put the code that checks the t > 50 condition inside the function, otherwise that will also only run once.
function below(t){
var button = document.getElementById('btun');
var quadrant = (t*t + 2*t + 1)+"px";
console.log('ye');
button.style.marginTop = quadrant;
document.write(pix);
if(t >= 50){
clearInterval(doBelow);
}
}
var doBelow = setInterval(function() { below(t++); },1);
Note: Using document.write in the interval isn't a good idea. As it runs after the page is completed, it will open a new page to write to which replaces the current page.

setInterval with an Array

I'd like to use the setInterval function in jQuery in order to create an alert with the content of one array every 4 seconds. However my alerts show all the values of my array within a short amount of time and it stops for 4 seconds after having displayed all the values.
$.each(['html5', 'EDM', 'Coca Cola', 'creativity'], function(id,value) {
setInterval(function(){
alert(value);
}, 4000);
});
In this case, I'd like to display something like : Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - Alert('Coca Cola') - 4 seconds - Alert('creativity') - 4 seconds - Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - ...
Move the setInterval from the loop.
var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var index = 0;
setInterval(function() {
console.log(arr[index++ % arr.length]);
}, 4000);​
Live DEMO
No jQuery needed.
Use a recursive setTimeout
var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var alertLoop = function(i) {
if (arr[i]) {
alert(arr[i]);
setTimeout(function(){alertLoop(i+1);}, 4000);
}
}
alertLoop(0);
Demo: http://jsfiddle.net/B5tJw/
Use of setInterval is discouraged. For an explanation, read here: http://bonsaiden.github.com/JavaScript-Garden/#other.timeouts
To summarise the problem:
setInterval fires the event at a regular interval, regardless of what else is happening on the page.
However, Javascript is not multi-threaded: it can only run one code sequence at a time. If setInterval is triggered while another code sequence is being run, the new code sequence will be blocked until the previous one is finished, and will wait for it.
If this happens repeatedly, you can end up with a large number of events waiting to be run.
You're using alert() to display your messages. alert() causes the code execution sequence to pause until the user responds to the message, but keeps it locked, so that other events cannot run their code. This is a particular problem for setInterval, because it fires new events at the specified time, regardless of whether something else is blocking the script.
The solution is to use setTimeout instead of setInterval.
setTimeout is only triggered once, but it is easy to tell it to trigger itself again inside its own function, so you can get the same effect as setInterval, but with much more control. Your code can wait until after the alert() has been accepted by the user before triggering the next event, which means that you won't get the problem of cascading events that can happen with setInterval.
Hope that helps explain things. The link I mentioned at the beginning is also very helpful.

setTimeout ignores timeout? (Fires immediately) [duplicate]

This question already has answers here:
Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
(3 answers)
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
This is my first real dive into JavaScript. Sure I've used it before, but I've never really written anything from scratch.
Anyway, I'm having a very strange problem that I hope someone can figure out for me.
I'm trying to make the text from a div fade from black to white. Simple, yeah?
The following code works. It will change the color to white, however, the setTimeout time of 500ms is being ignored.
If you use Chrome and look at the JS console, you'll easily see that the doFade() method is being called almost instantaneously, not every 500 milliseconds.
Can anyone explain this?
var started = false;
var newColor;
var div;
var hex = 0;
function fadestart(){
if (typeof fadestart.storedColor == 'undefined') {
div = document.getElementById('test');
fadestart.storedColor = div.style.color;
}
if(!started){
console.log('fadestart');
newColor = fadestart.storedColor;
started = true;
setTimeout(doFade(), 500);
}
}
function fadestop(){
console.log('fadestop');
div.style.color = fadestart.storedColor;
started = false;
hex = 0;
}
function doFade(){
if(hex<=238){
console.log(hex);
hex+=17;
div.style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout(doFade(), 500);
}
}
You need to get rid of the parentheses on doFade().
The parentheses invoke the function instantly.
Just use this in stead: doFade
setTimeout(doFade(), 500);
This line says "execute doFade(), then pass whatever value it returns to setTimeout, which will execute this return value after 500 milliseconds." I.e., you're calling doFade() right there on the spot.
Skip the parentheses to pass the function to setTimeout:
setTimeout(doFade, 500);
I think you should use setTimeout(doFade, 500); or setTimeout("doFade()", 500);

Categories

Resources