When I activate showMoves() the setInterval is supposed to repeat the function one second at a time.
However, it speeds up after a few seconds and activates the function several times in a single second instead of once. Also the clearInterval isn't working even though the if statement for it turns true.
let i = -1;
function showMoves() {
const start = setInterval(showMoves, 1000);
if (i > game.computerMoves.length) {
clearInterval(start);
}
console.log(i + ' ' + game.computerMoves.length);
const showColors = new Map([
[green, 'lime'],
[yellow, 'rgb(255,255,102)'],
[blue, 'dodgerblue'],
[red, 'salmon'],
]);
i++;
let move = game.computerMoves[i];
move.style.backgroundColor = showColors.get(move);
}
You shouldn't be calling setInterval inside the very same function that's being called by setInterval -- you're setting up multiple interval timers that way, not just one that you can clear away easily. It's "speeding up" as you say because you're seeing more and more different interval timers calling the same function.
You're recursively calling showMoves - every second, a new interval is created. When the function runs and the stop condition isn't reached, the start reference you have to the interval you just created is just garbage collected. You want a method to save the intervals so that you can reference them later so they can be cleared. For example:
let intervals = [];
function showMoves() {
intervals.push(setInterval(showMoves, 1000));
if (i > game.computerMoves.length) {
// clear all currently running intervals:
intervals.forEach(clearInterval);
intervals = [];
}
// ...
Related
This time go faster if is called 2 times, 3 times faster and so on.
function startIdleTime() {
var ciclo;
function startSlidercicle() {
ciclo = setInterval( function() {
let seconds = parseInt(sessionStorage.getItem('idle'));
seconds += 1;
sessionStorage.setItem('idle', seconds);
}, 1000);
}
// start idle counter
if (!sessionStorage.getItem('idle')) {
alert('non esiste timer, lo imposto')
sessionStorage.setItem('idle', 0);
alert(3)
}
if (sessionStorage.getItem('idle') > 15) {
anotherFunction();
}
if (sessionStorage.getItem('idle') < 15 || !sessionStorage.getItem('idle')) {
clearInterval(ciclo);
startSlidercicle();
}
}
I need to set idle time. When 15 i'll call an other function,
if <= 15 I reset only a counter to 0
But if is called few times my count go faster then 1sec }, 1000);)
Looks like the interval is not cleared before instantiating a new one. The result will be several intervals that will be executed with a different phase, and it will look like it's running with a shorter interval.
The reason for this behavior is that you are not clearing the interval, because you are creating a new ciclo variable every time you call the startIdleTime function. Probably you want the variable ciclo to be global, in order to share the interval handler across the function calls. You need to widen the scope, and to widen the scope you can just move the variable declaration out of the function definition:
var ciclo;
function startIdleTime() {
function startSlidercicle() {
Also note that in the following line:
sessionStorage.getItem('idle') < 15 || !sessionStorage.getItem('idle')
the second part is never evaluated. Let's suppose that getItem returns null: then null < 15 is true, so the check becomes useless
I need to modify existing slider. Its slides now have differing data-seconds added to it and need be active that long. Previously I had:
var slidePause = 10;
function startSlideBanner() {
bannerTimer = setInterval(nextSlide, slidePause * 1000);
}
startSlideBanner();
Which worked infinitely well. Now I would need to update slidePause variable every iteration. Looking for an example if its possible.
No: You cannot do it with setInterval. Once it is set, it may only be cancelled.
What you can do however, is use setTimeout to achieve your goals. While this can be done recursively, I prefer to take advantage of promises to do it iteratively:
const wait = ms => new Promise(res => setTimeout(res, ms));
let slidePause = 10;
async function startSlideBanner() {
while(true) {
await wait(slidePause * 1000);
nextSlide();
// Example: Double the time for each slide
slidePause = slidePause * 2;
}
}
startSlideBanner();
One of the problems with setInterval() is that JavaScript's single threaded nature can result in uneven periods between the setInterval() code being fired. To avoid this, run setInterval() at a faster rate, and calculate the time passed to determine whether an action should be taken.
If you make the calculation for time passed dependent on a variable you can change the effective rate at which the event occurs.
function nextSlide(period){
console.log("Next Slide in "+period);
}
function VariableTimer(period, startImmediately = true) {
this.period = period;
self = this;
this.startTime = startImmediately?0:Date.now();
this.time = setInterval(function(){
if (Date.now()-self.startTime > self.period*1000) {
self.startTime = Date.now();
nextSlide(self.period);
}
}, 100); // Run setInterval at 100ms intervals.
this.stop = function(){
clearInterval(self.time);
}
}
let timer = new VariableTimer(10);
// Change the timer period like this
// timer.period = 5;
// After 20 seconds switch to 5 second intervals
setTimeout(function(){timer.period = 5;},20000);
// After 40 seconds, stop the timer.
setTimeout(function(){timer.stop();console.log("timer stopped")}, 40000);
I'm busy building a flash-card game. I want to give the user a visible countdown before a card get's flashed on screen. My script for the countdown looks like this:
let downSeconds = 5;
while (downSeconds > 0) {
setTimeout(function() {
$("#timerDisplay").text = downSeconds;
downSeconds--;
}, 1000);
}
$(".detail-card").removeClass("hidden");
If I didn't want the updated seconds I'd just use a 5000ms 'setTimeOut'. I did before try with a setInterval, with a delay of 1000ms, so every time it elapses it updates the seconds.
Now, if I put a breakpoint on either line of the setTimeOut callback, and only there, nothing happens when the setTimeout is invoked, so the seconds display never updates, and I'm in an infinite loop, because downSeconds--; is never invoked, so downSeconds keeps the value of 5 all throughout.
What am I doing wrong?
setTimeout runs the code later, while the while loop runs "now". You can't successfully combine the two.. So, you have to write your code differently, something like this should work:
let downSeconds = 5;
function doCountDown() {
downSeconds--;
$("#timerDisplay").text = downSeconds;
if (downSeconds > 0) {
setTimeout(doCountDown, 1000);
} else {
$(".detail-card").removeClass("hidden");
}
}
setTimeout(doCountDown, 1000);
You may use ES7 and await the loop for a second:
const time = ms => new Promise(res => setTimeout(res,ms));
(async function(){
let downSeconds = 5;
while (downSeconds > 0) {
await time(1000);
$("#timerDisplay").text = downSeconds;
downSeconds--;
}
$(".detail-card").removeClass("hidden");
})()
The setTimeout call is asynchronous,
and so by the time the 1000 milliseconds scheduled by the first call to setTimeout elapses,
the while-loop will have executed its body thousands of times,
each time scheduling a new job with setTimeout,
causing massive scheduling work to the JavaScript engine.
The engine is too busy to execute the function,
and it just keeps getting worse,
as the loop keeps running and keeps scheduling more and more.
I would expect your execution environment to become unresponsive and unable to make progress, unable to actually call the first function scheduled.
Use setInterval and clearInterval instead, for example:
let counter = 5;
let interval = setInterval(() => {
$("#timerDisplay").text = counter;
counter--;
if (counter == 0) {
clearInterval(interval);
$(".detail-card").removeClass("hidden");
}
}, 1000);
Learning about callbacks and the solution to this problem eludes me.
It should print a number every second counting down until zero. Currently, it logs the numbers from 10 - 0 but all at once and continues in an infinite loop.
Please help me to gain a better understanding of this situation. I have read up on callbacks and have a conceptual understanding but execution is still a bit tricky.
var seconds = 0;
var countDown = function(){
for(var cnt = 10; cnt > 0; cnt--){
setTimeout(function(x){
return function(){
seconds++
console.log(x);
};
}(cnt), seconds * 1000);
}
}
countDown()
The way your code is working now, it executes a for loop with cnt going from 10 to 1. This works. On each iteration, it schedules a new function to be run in seconds * 1000 milliseconds, carefully and properly isolating the value of cnt in x each time. The problem is that seconds is 0, and it will only be changed once a callback executes; but by the time a callback executes, all of them will already have been scheduled for execution. If you need seconds * 1000 to vary while you’re still scheduling them all (while the for loop is still running), you need to change seconds in the loop, rather than inside one of the callbacks.
Read up on IIFEs to see how they work. In this situation, you're creating a closure of the value you want to print. You had the right idea, but your syntax was off.
var seconds = 0;
var countDown = function () {
var cnt = 10;
// simplify your loop
while (cnt--) {
// setTimeout expects a function
// use an IIFE to capture the current value to log
setTimeout((function (x) {
// return the function that setTimeout will execute
return function (){
console.log(x + 1);
};
}(cnt)), (++seconds) * 1000);
}
};
countDown();
Let's say there is a set of Watchers that need to be refreshed periodically. They each may have a different refresh interval. There may be several hundred such Watcher items at any given moment. The refresh time for any Watcher can range from a second to several minutes or hours.
Which is better?
Use a separate setTimeout for each one.
Use a setInterval that runs a function every second. The functions then cycles through each Watcher checking to see if it needs to be refreshed.
At first I assumed that the native code implementation of setTimeout would be more efficient than a JS function that does checking, but it's really a question of how setTimeout is implemented, how much overhead each timeout takes on a per-tick basis, and how well the number of timeouts scales.
I'm asking this for a Node application so the specific engine I'm referring to is V8, but it'd be cool if anyone knows the details for other engines as well.
Here's one idea that should be pretty efficient regardless of how setTimeout or setInterval is implemented. If you have N events scheduled for N different times in the future, create an array of objects where each object has a property for the time that the event is due and a property that tells you what type of event it is (a callback or some other identifier). Initially sort that array by the time property so the next time is at the front of the event and the furthest time is at the end.
Then, look at the front of the array, calc the time until that event and do setTimeout() for that duration. When the setTimeout() fires, look at the start of the array and process all events who's time has been reached. If, after processing an event, you need to schedule it's next occurrence, calc the time in the future when it should fire and walk the array from start to finish until you find an event that is after it and insert this one right before that event (to keep the array in sorted order). If none is found, insert it at the end. After processing all events from the front of the array who's time has been reached, calc the delta time to the event at the front of the array and issue a new setTimeout() for that interval.
Here's some pseudo-code:
function orderedQueue() {
this.list = [];
}
orderedQueue.prototype = {
add: function(time, callback) {
var item = {}, added = false;
item.time = time;
item.cb = callback;
for (var i = this.list.length - 1; i >= 0; i--) {
if (time > this.list[i].time) {
// insert after the i item
this.list.splice(i + 1, 0, item);
added = true;
break;
}
}
// if no item was after this item,
// then put this on the front of the array
if (!added) {
this.list.unshift(item);
}
},
addDelta(delta, callback) {
var now = new Date().getTime();
this.add(now + delta, callback);
},
waitNext: function() {
// assumes this.list is properly sorted by time
var now = new Date().getTime();
var self = this;
if (this.list.length > 0) {
// set a timer for the first item in the list
setTimeout(function() {
self.process();
}, this.list[0].time - now);
}
},
process: function() {
var now,item;
// call all callbacks who's time has been reached
while (this.list.length) {
now = new Date().getTime();
if (this.list[0].time <= now) {
// remove front item from the list
item = this.list.shift();
// call the callback and pass it the queue
item.cb(this);
} else {
break;
}
}
// schedule the next item
this.waitNext();
}
}
And, here's generally how you would use it:
var q = new orderedQueue();
// put initial events in the queue
q.addDelta(100, f1);
q.addDelta(1000, f2);
q.addDelta(5000, f3);
q.addDelta(10000, f4);
q.addDelta(200, f5);
q.addDelta(100, f1);
q.addDelta(500, f1);
// start processing of queue events
q.waitNext();