I am new to JS.
I need an array variable which is used to display the values periodically every 1s using setInterval() inside a function.
The array variable for ex intV[] (setInterval variable) should display the values when used in console.log(intV[]); and the values should be stored in intV[].
I tried the below code,
But it didn't work.
function date() {
var currentDate = Date.now();
var val = String(currentDate).substr(8, 2);
return val;
}
var intV = [];
function mockData(v) {
var v = document.getElementById('sample');
//setInterval function
intV[v] = setInterval(date, 1000);
console.log(intV[v]);
}
When I did console.log(intV[v]);. It doesn't display the values every 1s. Instead, it gives a static value Which is not updated every 1s.
How could i store the values, which is updated every 1s in the intV[].?
Could someone please help?
Many thanks.
The setInterval method expects a function as a parameter which is run at each specified interval. All of the logic, including console.log needs to be inside of the function that you pass to setInterval. I believe the sample provided below provides what you are looking for, but you need to understand that the intV array will be populated AS the intervals occur, NOT before.
var intV = [];
function date() {
var currentDate = Date.now();
var val = String(currentDate).substr(8, 2);
intV.push(val);
console.log(intV[intV.length - 1])
}
//setInterval function
setInterval(date, 1000);
Related
I want a function that looks for elements with the "comment" class, and if the number of comments has changed, (if there is a new comment) it will call an other function. So this is what I did:
function main(num0){
var comments = document.getElementsByClassName("comment");
var num = comments.length;
if (num!=num0){
//function to call();
console.log("New Comment");
}
setTimeout(main(num),10); //check every 10 for new comments
}
main(0);
num0 is the number of comments the last time the function was called so I try to recall the same function but num0 takes the value of num, but it doesn't seems to work.
I recommend using setInterval. calling recursion at higher rate may cause different errors after some time.
let num = 0;
setInterval(()=>{
var comments = document.getElementsByClassName("comment");
var num1 = comments.length;
if (num!=num1){
//function to call();
console.log("New Comment");
num=num1
}
},10)
Your use of setTimeout is invalid; you are calling the function main instead of providing setTimeout with a callback. I also believe you need to pass num0 instead of num in your timeout.
Try this:
function main(num0){
var comments = document.getElementsByClassName("comment");
var num = comments.length;
if (num!=num0){
//function to call();
console.log("New Comment");
}
setTimeout(main, 10, num0); // Changed this line
}
main(0);
Review this regarding the setTimeout function:
https://www.w3schools.com/jsref/met_win_settimeout.asp
setTimeout takes a function reference. In your case you aren't passing the reference, you are passing the result of that function by calling it.
Example of syntax that does what you intend it to do:
setTimeout(() => main(num),10); //check every 10 for new comments
https://www.w3schools.com/jsref/met_win_settimeout.asp
I'm very new to coding (2 weeks experience) so please bare with my silly question about this code. Ultimately I want it to continuously run the function called "timer," which tells me how long it took to run the function called "add," display that result on my screen, and then update that results each time it runs.
function add(a,b){
return a + b;
}
function timer(){
var a = Math.floor(Math.random() * 101);
var b = Math.floor(Math.random() * 101);
var start = performance.now();
add();
var end = performance.now();
var duration = end - start;
return duration + ' milliseconds';
}
t = setInterval(timer,1000);
What this seems to do is return the number "1" and do nothing after.
Now when I replace
return duration + ' milliseconds'
with
console.log(duration + ' milliseconds')
it does what I want, except for the fact that the reason I don't want to use console.log is that it jumps to a new line when displaying the duration instead of replacing the previous line with the new duration. To clarify, I don't want a big list of durations that gets longer every time it runs, I just one one duration displayed, that gets updated and replaced each time it runs.
Thank you for your help!
setInterval is asynchronous so you will not get your return value this way. The number you are getting back is an ID for later when you want to clearInterval.
But let's say for fun setInterval did try to return your value.
You do t = setInterval(...) but when that happens your code inside of setInterval hasn't executed yet. It was just placed in the queue at that moment but the assignment of t = ... isn't waiting around.
maybe this could help https://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027
You are setting t to the return value of setInterval()
The documentation says that setInterval() returns the following:
timeoutID ... a numeric, non-zero value which identifies the timer
It seems like what you actually want is to set the variable t somewhere inside timer(), so that when setInterval() calls it every 1000ms, it'll update t.
The function console.log appends to the console. So you will have to clear the console to achieve what you want.
If you are on chrome then call the
clear()
before
console.log() in timer function.
Hope it helps
If you want to be notified when setInterval is finished then you may need to use a promise:
function add(a,b) {
return a + b;
}
function timer(delayTime) {
return new Promise(
function(resolve) {
setInterval(
function() {
var a = Math.floor(Math.random() * 101);
var b = Math.floor(Math.random() * 101);
var start = performance.now();
add();
var end = performance.now();
var duration = end - start;
resolve(duration + ' milliseconds');
}, delayTime
);
}
);
}
timer(1000).then(
function(t) {
console.log(t);
}
);
When you say
display that result on my screen
I'm thinking you may be just looking to update an element's text. If you simply want to keep track of it, you will need to use a variable outside of the timer function and update that variable inside the function. As others have pointed, setInterval will return an ID for retrieving the interval later. For example, if you wanted to stop the timer, you would do clearInterval(t);
I created a code snippet that updates the duration on the screen every time:
function add(a,b){
return a + b;
}
function timer(){
var a = Math.floor(Math.random() * 101);
var b = Math.floor(Math.random() * 101);
var start = performance.now();
add();
var end = performance.now();
var duration = end - start;
document.getElementById('duration').innerHTML = duration + ' milliseconds';
}
t = setInterval(timer,1000);
Duration: <span id="duration"></span>
Also, take a look at this, since you are new to coding: How do I return the response from an asynchronous call?
I've modified this existing countdown timer so that I can run multiple countdown and used session to display the timer in HTML. The runCountdown function now looks like this:
runCountdown(object, param, sessionName)
object is used instead of var myCounter of the solution. param is for countdown seconds. sessionName is for storing count current second to show it in the browser dynamically.
Now I want to run several countdown timer simultaneously , thus in the Meteor app I've done something like this
Meteor.call('doCount', function(error, result) {
if ( !result < 1 ) {
counters = new Array(result);
var queryResult = ProductList.find().fetch();
for (i = 0; i < counters.length; i++) {
var diff = queryResult[i].expire - Math.floor(TimeSync.serverTime() / 1000);
runCountdown(counters[i], diff, queryResult[i]._id);
}
console.log('testing from doCount ' + counters[0]);
}
});
doCount returns the number of Countdown Timers I want to run in the browser.
Now the weird thing is that my runCountdown function inside the for loop is working properly as I can see from the browser console, which implies that counters variable is being used this function. Obviously my main objective is not to log the object but it's showing undefined.
Why is that happening?
The runCountdown function
function runCountdown(obj,param,sessionName){
obj = new Countdown({
seconds:param, // number of seconds to count down
onUpdateStatus:
function(sec){
Session.set(sessionName,sec);
console.log(Session.get(sessionName));
}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
obj.start();
}
You're expecting to store the obj object to be available outside then return the obj from the runCountdown function and store it in the counters[i] array item.
function runCountdown(param,sessionName){
obj = new Countdown({
seconds:param, // number of seconds to count down
onUpdateStatus:
function(sec){
Session.set(sessionName,sec);
console.log(Session.get(sessionName));
}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
obj.start();
return obj;}
now in your array structure store this object in the following way -
counters[i] = runCountdown(diff, queryResult[i]._id);
I am confused on the difference between this syntax:
var timerId;
function clockStart(){
// debugger;
if(timerId){
return;
}
update();
// THIS LINE BELOW *********************************************
var timerId = setTimeout(function(){clockStart()}, 1000);
}
function clockStop(){
timerId = null;
}
function update(){
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if(hours < 10) {
hours = '0'+hours;
}
document.getElementById('hour').innerHTML = hours;
if(minutes < 10){
minutes = 0+minutes;
}
document.getElementById('min').innerHTML = minutes;
if(seconds < 10){
seconds = '0' + seconds;
}
document.getElementById('sec').innerHTML = seconds;
}
I provided both functions being called but the main part of this function I do not understand is why I need to pass an anonymous function to call my clockStart() function.
My function works when I use this syntax:
var timerId = setTimeout(function(){clockStart()}, 1000);
But it doesn't work when I use:
var timerId = setTimeout(clockStart(), 1000);
I have been working a while on these two functions and I honestly stumbled upon this by accident. I really don't see what the anonymous function is doing besides invoking my clockStart function. But in my opinion, my clockStart() function should be invoked every second(1000ms) since it is calling itself, so why does it need an anonymous function to invoke it? Shouldn't it be invoking itself?
If you would like to see this digital 'clock's' full code please checkout my codepen link.
This line:
var timerId = setTimeout(clockStart(), 1000);
is calling clockStart() immediately and passing the return result from that function to setTimeout(). Since the function doesn't return anything, you're effectively doing this:
clockStart();
var timerId = setTimeout(undefined, 1000);
which obviously doesn't do what you want.
You can use this instead:
var timerId = setTimeout(clockStart, 1000);
In this case, you want to pass a function reference to setTimeout() which means you do not include the parens. When you include the parens, that means to execute it NOW. When you just pass the name of the function, that is just a reference to the function (think of it like a handle) by which setTimeout() can call it later. That's what you want.
When you do this:
var timerId = setTimeout(function(){clockStart()}, 1000)
you're just defining an anonymous function and passing a reference to that anonymous function to to setTimeout() which works fine, but is not necessary in this case since you can just pass the clockStart name as in my third code example above.
Since you asked about how a function can call something later, I'll show you a simple example. Here's a function that takes a starting value, an ending value, an increment and a callback function. This will call the callback and pass it the value that it's incrementing until the value exceeds the end value.
// define an increment function that will call a callback
// multiple times based on the start, end and increment arguments
function eachIncrement(start, end, increment, callback) {
// the function argument named callback contains
// a function reference
var val = start;
while (val <= end) {
// execute the function reference and
// pass it the current val
callback(val);
val += increment;
}
}
// define a function that we want to be called later
function processValues(num) {
// this will get called multiple times with
// values 1, 4, 7, 10
}
// set up the increment parameters and pass a function reference
eachIncrement(1, 10, 3, processValues);
I'm trying to create a random quote generator. I have created a function called timer that runs another function pickQuote every 400ms but at the moment this doesn't seem to work. in pickQuote I run a function randomNumberGen that creates a random number. My problem in the randomNumberGen is that I want to have an if or if..else in place that checks whether or not the new random number is different from the current quotes[randomNumber] but i'm unsure how to do this.
Can anyone provide me with some insight on how I can achieve this?
My current effort can be viewed here: http://jsbin.com/aqinud/12/edit
index is not defined outside $.each. Variables in functions are not accessible outside it if you use var.
What I recommend is altering the function as follows:
function randomNumberGen() {
//generate randomNumber based on length of array
// round it down (parseInt is for string->number conversion)
var thisRandomNumber = Math.floor(Math.random() * len);
if ( randomNumber === thisRandomNumber ) {
randomNumberGen();
} else {
randomNumber = thisRandomNumber;
}
}
So, first create a random number and only if it's different from randomNumber, update it with the newly created one. Otherwise, try again.
Also, setTimeout requires a function, so don't invoke it yet:
runQuotePicker = setInterval(pickQuote, 400);
http://jsbin.com/aqinud/13/edit
Perhaps something like this:
var currentNumber = -1;
function randomNumberGen() {
var num = parseInt(Math.random() * (len) );
if(currentNumber != num){
currentNumber = num;
return num;
} else {
return randomNumberGen();
}
}
I noticed you had incorrectly passed 'pickQuote' to setInterval. Try wrapping the callback in an anonymous function:
function timer() {
runQuotePicker = setInterval(function(){
pickQuote();
}, 1000);
}
Otherwise you're scheduling the result of pickQuote to be invoked ever x milliseconds.