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

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.

Related

Can anyone explain the working of the following recursive function?

I want to know that the following code is return number from 10 to 1 but after doing that it calls itself again 10 times but not doing anything. I tried to understand the code step by step with the help of the debugger variable but was not able to.
let countDown = function f(fromNumber) {
console.log(fromNumber);
let nextNumber = fromNumber - 1;
if (nextNumber > 0) {
f(nextNumber);
}
}
let newYearCountDown = countDown;
countDown = null;
newYearCountDown(10);
For more reference, please visit Javascripttutorial to know more about the code.
Recursion is a process of calling itself. A function that calls itself is called a recursive function. In your example, your first function doesn't get completed, but it's if condition is what is being run. During the if condition, your function is more like put on hold as another call is made. Your first function waits for it to complete.
In this fashion, 10 function calls are made and all are waiting inside the if condition. After the last condition (nextNumber == 0) fails, the function returns back to the 9th function where the if condition was waiting. Similarly, all your functions will get completed one by one from 9 to 1.

setTimeout function in jQuery not working [duplicate]

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.

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)

UserScript Timer Error

Okay, so there is a button on a page that I'm trying to change the text of for a count-down done in Javascript. I'm fairly new to the language (2 days), and am not sure as to what is wrong with my code. Instead of waiting the full second before iterating again, it instantly re-iterates.
var c = 15;
function countDown(e){
if (c!=0){
e.value = 'Reply (' + c + ')';
c--;
setTimeout(countdown(e),1000);
}
else{
e.value = 'Reply'}
}
}
but it seems that instead of taking 15 seconds like I assumed, it fires off all at once (proven by me adding in an alert('a'); in the if statement I could see the button text changing)
I'm not sure if it's a problem with Greasemonkey or a problem with my javascript.
Your problem is with this line:
setTimeout(countdown(e),1000);
countdown(e) is a call to the countdown function that returns void. The setTimeout function accepts a function reference and a timeout, so you need to change it to:
setTimeout(countdown, 1000);
Your current code is calling countdown(e) 15 times recursively and then setTimeout(void, 1000);
If you need setTimeout to pass arguments (like e) to your function you can make use of the optional parameters after the timeout.
setTimeout(countdown, 1000, e);

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