setInterval not continuing [duplicate] - javascript

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)

Related

Assigning each element of an array (one at a time) to a variable for a specific amount of time

I have an array with a list of elements(users in this case ).I have a variable called currentBeneficiary. I want to assign each user to be a currentBeneficiary for a specific amount of time like 10m,then we move on to the next member of array and assign them to the variable(currentBeneficiary) for same amount of time so on. I have used SetInterval() and it assigns an element of the array to the variable just for 1s after the specified period of time.And as mentioned i just want the vice versa.How can i achieve this kindly?
const members = merrygoround.members
let currentbeneficiary
if(merrygoround.interval === "daily"){
function DelayArray(array, delegate, delay) {
var i = 0
var interval = setInterval(function() {
delegate(array[i]);
if (i++ >= array.length - 1)
clearInterval(interval);
}, delay)
return interval
}
DelayArray(members, function(obj) {
currentbeneficiary = obj
console.log(`current beneficiary is ${currentbeneficiary}`)
},1000*60)
}
setInterval mean process will wait a "delay" before run your logic, after that wait a "delay" again. I am not sure I understand your question. I guess you want the first user must run right the moment DelayArray call, so you just call the delegate function for the first user before run DelayArray, variable i will start with 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.

Write a function that checks how many times another function will be called in a time interval

Say I have a function that logs "Hello" every 500 ms.
var logHello = function() {
setInterval(function(){
console.log("Hello");
}, 500);
};
Is there a way to write another function that will check if logHello gets called more than or equal to 1 time every second(without modifying the original logHello function).
In this case it will return true because Hello will get logged 2 times in 1 seconds.
I am assuming you want to do this for debug reasons, so I must warn you not to include this code in any production application, as it's really just meant for debugging. It's very cool that our solution works however it overwrites native javascript functionality which is typically frowned upon because it can cause code to behave differently than expected if you alter a native functions behaviour.
If it's a condition that you are not allowed to modify your code, you can simply overwrite javascript's setInterval, and use it as a "hook" into your function. We will modify setInterval to now track the time difference (seconds) inbetween calls to your method. We will then invoke and return the original setInterval method so that your code still works exactly as expected:
// keep a pointer to the original setInterval function
var oldSetInterval = window.setInterval;
// we will create our own setInterval function and put logging in it
window.setInterval = function(block, interval) {
var lastRunAt;
return oldSetInterval(function() {
// here is where we print how long it's been since the method last ran
if(lastRunAt) {
console.log("the interval last ran " + (Date.now()-lastRunAt)/1000 + " seconds ago");
}
lastRunAt = Date.now();
block();
}, interval);
}
And now running logHello() yields:
Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.505 seconds ago
This assumes you're running on the web. If you're in node, replace references to window with globals.

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.

Categories

Resources