executing a block of code at a certain exact time in javascript - javascript

I want to execute a block of code (which includes recursive setTimeout) at a certain exact time in javascript.By writing get_current function i get the current time and with setInterval method with 1 mili second interval i compare the current time( fetched from get_current function) with my desired time and if that condition satisfies i execute a block of code recursively. i test my code with console messages and i understand that only once this code is executed and if statement is checked only once.
could any one help me doing that???
var dateString;
var delay=1500;
function get_current() {
var mydate = new Date();
var mili_real = mydate.getMilliseconds();
var hour_real=mydate.getHours();
var minute_real=mydate.getMinutes();
var second_real=mydate.getSeconds();
if(minute_real<10)minute_real="0"+minute_real;
if(hour_real==0)hour_real="12";
if(second_real<10) second_real="0"+second_real;
if(mili_real<10)mili_real="00"+mili_real;
else if(mili_real<100) mili_real="0"+mili_real;
dateString=hour_real+""+minute_real+""+second_real+""+mili_real;
}
setInterval(checkStart(),1);
function checkStart() {
get_current();
if (dateString == 145412578) {
var timerId = setTimeout(
function request() {
console.log("request"+delay);
if(delay<1600){
delay++;
} else {
delay--;
}
timerId=setTimeout(request,dealy);
}, delay);
} else {
console.log("waiting to start");
}
}

First, let's take a look at the docs: It says that setInterval takes two main parameters. There are optionally additional parameters to pass to the function when it's called, but let's ignore those and focus on the first two parameters. The second parameter is the time in milliseconds, which is clear for you. The first parameter is a function. Let's see your call
setInterval(checkStart(),1);
You pass checkStart() as your first parameter. It's a function call. There is no return in that function, which means that it "returns" undefined. So, your code above is functionally equivalent with the following:
checkStart();
setInterval(undefined,1);
So, the solution should be to pass the function instead its result to setInterval:
setInterval(checkStart,1);
and as a result, checkStart should be regularly called.

Related

settimeout this. RangeError: Maximum call stack size exceeded

Why RangeError: Maximum call stack size exceeded in this.startTime();
startTime() {
$('.m-codeModal-resendTimer').html(this.sectmr);
this.sectmr--;
if (this.sectmr < 0) {
this.sectmr = 0;
$('.m-codeModal-resendErrorNow').fadeIn(0);
$('.m-codeModal-resendErrorSec').fadeOut(0);
$('.m-codeModal-sorry').fadeOut(0);
}
setTimeout(this.startTime(), 1000);
}
Several things...
Add a function keyword to define your startTime function.
Remove the this keyword in the setTimeout reference to startTime.
The function setTimeout takes a callback as a parameter. You, instead of passing a callback parameter to the function, are actually calling the startTime function before the setTimeout function ever has a chance to evaluate and count down 1000 milliseconds.
Here's a simplified example:
var count = 0;
function startTime() {
count++;
document.getElementById('count').innerHTML = count;
setTimeout(startTime, 1000);
}
startTime();
<div id="count"></div>
You're in an infinite loop.
by calling startTime() function call for the first time, you are recursively calling startTime again once you enter the setTimeout function.
In your startTime() function as it is now, there is no way to exit it once you enter.
Maybe you'd want to try
if (this.sectmr < 0) {
...
return;
}
by adding the return statement, once your sectmr goes below zero and enters the if loop, you should be kicked out of the function. I'm not sure what your end goal is, however. Please be a bit more descriptive in the opening question.
The problem is that you're doing setTimeout(this.startTime(), 1000);, executing this.startTime() and using its return value (undefined in this case) as the timer handler. Just remove the ().

How to make part of a function only execute once until it's allowed to do otherwise

How can I call a javascript function (repeatedFunction()) repeatedly but make it so that, let's say an alert("This function is being executed for the first time"), is only activated the first time that repeatedFunction() is, but the //other code is always activated? And also, how can I make the alert() allowed to be activated for one more time, like if the repeatedFunction() was being executed for the first time again?
You can set a flag. Say for example, you have this following code:
var flagAlertExecd = false;
function repeatThis () {
if (!flagAlertExecd) {
alert("Only once...");
flagAlertExecd = true;
}
// Repeating code.
}
And to repeat this code, it is good to use setInterval.
setInterval(repeatThis, 1000);
Functions are objects. You can set (and later clear) a flag on the function if you like:
function repeatedFunction() {
if (!repeatedFunction.suppress) {
alert("This function is being executed for the first time");
repeatedFunction.suppress = true;
}
// ...other code here...
}
When you want to reset that, any code with access to repeatedFunction can clear the repeatedFunction.suppress flag:
repeatedFunction.suppress = false;
The flag doesn't have to be on the function, of course, you could use a separate variable.
That said, I would suggest looking at the larger picture and examining whether the alert in question should really be part of the function at all.
JavaScript closure approach will fit in this task. It has no global variables, and keeps your task in a single function.
var closureFunc = function(){
var numberOfCalls = 0;
return function(){
if(numberOfCalls===0)
{
console.log('first run');
}
numberOfCalls++;
console.log(numberOfCalls);
};
};
var a = closureFunc(); //0
a(); //1
a(); //2
var a = closureFunc(); //drop numberOfCalls to 0
a(); //1
http://jsfiddle.net/hmkuchhn/
You can do it by declaring a variable and incrementing it in your function. Using an if statement, you can check how many times it has been triggered. Code :
var count = 0;
function myfunc(){
if(count==0){
alert("Triggering for the first time");
count++;
}
//Your always triggering code here
}
Demo
This even tracks record of the how many times the function is triggered. It can be useful if you don't want to execute the alert() on nth time.
You can also use boolean values. Like this :
var firstTime = true;
function myfunc(){
if(firstTime){
alert("Triggering for the first time");
firstTime = false;
}
//Your always triggering code here
}
Demo
The second approach will not track the record of how many times the function has been triggered, it will just determine that whether the function is being invoked for the first time or not.
Both the approaches work fine for your purpose.
var firstTime = true;
var myFunction = function() {
if(firstTime) {
alert("This function is being executed for the first time");
firstTime=false;
}else{
//whatever you want to do...
}
}; //firstTime will be true for the first time, after then it will be false
var milliseconds = 1000;
setInterval(myFunction, milliseconds);
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second.

Output of one sample program of javascript is giving wrong answer

I was reading one book named 'Hands on node.js' by 'Pedro Teixiera'.
I was trying to execute one same program giving in that book that will call a function and that function is calling the same function recursively within some interval again and again.
But when I executed, it gives only one time '1' and stops
Please help me to figure it out why it is not able to call the same function again.
Sample program is as follows:
var schedule = function(timeout, callbackfunction) {
return {
start: function() {
setTimeout(callbackfunction, timeout)
}
};
};
(function()
{
var timeout = 10000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++ count);
schedule(timeout, doStuff);
}).start(timeout);
})();
You aren't actually calling the function again. start() is the part that starts the timer.
schedule( timeout, function doStuff() {
console.log( ++count );
schedule( timeout, doStuff ).start(); // <--- added .start() here
}).start();
(Also note that the start() function doesn't take parameters.)
with some interval again and again
No, for that you would have used setInterval instead of setTimeout.
it gives only one time '1' and stops
Yes, your doStuff function doesn't put a new timeout. Your odd schedule function needs to be .start()ed!

JavaScript self invoking function

I'm trying to understand this example code, what is the function of line 15, why start(timeout)? (Sorry, I'm new to programming)
var schedule = function (timeout, callbackfunction) {
return {
start: function () {
setTimeout(callbackfunction, timeout)
}
};
};
(function () {
var timeout = 1000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++count);
schedule(timeout, doStuff);
}).start(timeout);
})();
// "timeout" and "count" variables
// do not exist in this scope.
...why start(timeout)?
In that example, there's actually no reason for passing timeout into start, since start doesn't accept or use any arguments. The call may as well be .start().
What's happening is that schedule returns an object the schedule function creates, and one of the properties on that object is called start, which is a function. When start is called, it sets up a timed callback via setTimeout using the original timeout passed into schedule and the callback function passed into schedule.
The code calling schedule turns around and immediately calls the start function on the object it creates.
In the comments, Pointy points out (well, he would, wouldn't he?) that the callback function is calling schedule but not doing anything with the returned object, which is pointless — schedule doesn't do anything other than create and return the object, so not using the returned object makes the call pointless.
Here's the code with those two issues addressed:
var schedule = function (timeout, callbackfunction) {
return {
start: function () {
setTimeout(callbackfunction, timeout)
}
};
};
(function () {
var timeout = 1000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++count);
schedule(timeout, doStuff).start(); // <== Change here
}).start(); // <== And here
})();
It's not very good code, though, frankly, even with the fixes. There's no particularly good reason for creating a new object every time, and frankly if the book is meant to be teaching, this example could be a lot clearer. Inline named function expressions and calls to methods on objects returned by a function...absolutely fine, but not for teaching. Still, I don't know the context, so those comments come with a grain of salt.
Here's a reworked version of using the schedule function by reusing the object it returns, and being clear about what bit is happening when:
(function () {
var timeout = 1000; // 1 second
var count = 0;
// Create the schedule object
var scheduleObject = schedule(timeout, doStuff);
// Set up the first timed callback
scheduleObject.start();
// This is called by each timed callback
function doStuff() {
// Show the count
console.log(++count);
// Set up the next timed callback
scheduleObject.start();
}
})();
The function schedule is executed as a function. That function returns an object. Like you can see with the { start... }. With the returned object it calls out the start function. This is called chaining. So the start function is executed after is set the function.
What is strange is that the timeout is passed to the start function which has no parameters.

Javascript: Could not really understand the function return

It is maybe incredibly easy but I couldn't solve what was going on.
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
The only thing that actually confuses me is the a(num) part. What actually it does?Reminder: I really am asking because I'm not familiar with the javascript syntax.
When the function doSomething() is executed it is passed the parameter a,
a is also some function that is then called when setTimeout() expires after 1 second,
then calling the function a() passing the argument called num
Example usage:
// call doSomething() passing the test() function as an argument
doSomething(test);
// takes a number as an argument and shows an alert with that value
function test(number)
{
alert(number);
}
// takes a function as an argument that will perform a 1 second timeout then execute the function called a
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
It calls the function referenced by the variable a, using the value referenced by the variable num as an argument.
setTimeout returns a timeoutID which can be used to cancel it using clearTimeout, so if you run doSomething a lot of times you will get different integer numbers which represent different timeoutID.
In your case a must be a function so you can call it using the parameter num
Example:
function doSomethingElse (justANumber) {
return justANumber + 1;
}
// Here you call your function
doSomething(doSomethingElse);
// or another special case
doSomething(function (justANumber) {return justANumber + 1;});

Categories