Is it possible to implement an equivalent of setTimeout() in javascript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is it possible to implement a function equivalent of setTimeout() in JavaScript? If yes, what would be the best way to do that?
function setTimeout(callback, time_in_ms)
{
// Implementation of time elapse of time_in_ms
callback();
}
I am asking this question out of curiosity. A simple "No, it is not possible" would also be an enough answer to this question.

Can I implement setTimeout() in javascript myself?
No - not without some other natively asynchronous API. You might be able to implement it in terms of setInterval, with web workers, requestAnimationFrame or really anything that runs in the same event loop as setTimeout would. But if there is a reason that prevents you from using the builtin setTimeout, there probably are also other issues with your environment - so it depends on the specific situation.

A synchronous (non-asynchronous) setTimeout equivalent would be something like this:
function myTimeout(fun, milisecs) {
var nowT = Date.now();
while(Date.now()< nowT+milisecs){
continue;
}
fun();
}
function consout() {
console.log('The future arrived now!');
}
myTimeout(consout,2000);
However, as Bergi mentioned you probably want an asynchronous API to avoid stalling the JavaScript execution of your browser.
A Worker has multi-thread capabilities to allow this, with functions such as myWorker.port.start() and myWorker.terminate()... I have never needed to create something with Workers or similar APIs, but perhaps you may research a little bit more in this field (I also should not complete your homework, if that is the case).

Related

Is await considered a bad coding practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm new to asynchronous programming and I would like to know if using await is considered a bad coding practice. I am asking this because it looks like it is possible to let the callback function do the waiting instead of letting the entire program suspend everythng until the rpocess complete.
Thank you and I appreciate your idea on this.
No, it’s not. It’s just an approach (very useful sometimes).
In modern systems complexity is so high, that in many cases having clear code is much better that having super effective code. Just an example: imagine the case when you need to make several async things one by one (maybe, fetch data based one previously fetched results). You can do it making a chain of several .then(). After that you’ll need to also add .catch(). And at this point you’ll find yourself writing spaghetti code which is a bit messy.
The other option is just make this async function with sequential calls and some logic between them. And this will look much better

Asynchronous programming in JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I often hear something like "working knowledge of asynchronous programming" regards JavaScript in job descriptions etc, but I'm not sure what it mean - is it about callbacks and promises or is there something else to it? I'd appreciate if someone could explain this to me.
Yes, effectively. More generally, it's about understanding the asynchronous nature of the most common JavaScript environments (web browsers, Node.js) and being fully versed in using callbacks, promises, async/await (in modern environments), etc. Understanding the closures-in-loops problem, why you can't return the result from an asynchronous call, that code that looks like it's below other code in a function may run earlier than the code apparently above it (because the code above it is in a callback), etc.

Delay a jquery function without timer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have seen many stack or google answer, where to delay a function there is a suggestion for timer. But is there a way to delay a function with out using timer. Or other way is there a event where once a event for eg onclick or on blur is done check for the event end and call a function in a lazy manner without using timer.
The only way to delay execution of a function is to do so as a callback in response to something. I believe this pretty much always means you need to have a trigger in the native implementation, as JavaScript is single threaded and will run until it runs out of code to execute.
Typical things that trigger a function call from native code are
Timers firing
Events firing
Async operations completing (eg. Http requests).
Out of these the timer is the only practical one to execute a function later without interactions being required by the user.
So no, not really I'd the short answer.
You can read more about the JavaScript Event Loop at the Mozilla Docs

Which way is better to call a jquery function twice? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a javascript jquery function which I need to use twice, in 2 different files.
Now, the question is, which is the better way to implement it, performance-wise. Should I declare function global using 'window' variable, or should I declare the function in each of the files?
Please keep in mind that traffic is not an issue, the script will be used from the hard-drive.
Thanks for your help.
My answer follows the DRY Principle (Don't Repeat Yourself). If you put the function in both files, and later find a bug on Page #1, someone has to remember that the function is duplicated on Page #2 as well (in this case, assume the bug report says "Page #1 doesn't work properly"). From that bug report, would the developer know to also modify Page #2? To avoid the human error piece, I'd always recommend you don't copy/paste functions into multiple locations.
Performance wise, if you're not concerned about traffic, the difference is nanoseconds slower wrapping it in a shared function as you do have to create an additional stack frame for the shared function call that in turn calls jQuery, but we're really talking nanoseconds. For a few nanoseconds lost, I'd say DRY is the way to go.

Generic functions: JavaScript or PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
While working on a recent project, I began wondering when somebody may use JavaScript vs. PHP for a generic function. Take this basic function (in JS) as an example, which simply returns whether or not a number falls within a particular range:
function range(num, var1, var2) {
if ((num >= var1) && (num <= var2)) {
return true;
}
else {
return false;
}
}
For something that doesn't query a database, nor is it information that should be — or needs to be — indexed for SEO (I know by default JavaScript will not be indexed), then my inference would be that JavaScript would be sufficient. But at the same time, PHP could be as well.
Basically, if the ONLY point of the application were a simple function like above (not that I can see a reason for that, but I digress...), then which langauge would be better to write this in? JavaScript or PHP?
Would love any insight as to which would be the best method to use and why. I recognize there is no right or wrong answer necessarily, but would like to hear arguments for or against one over the other.
Thanks!
As you point out, there is no necessarily right or wrong answer.
I would say that it depends:
-Is it a problem for people to be able to reverse engineer the code?
-Is it a problem if it does not execute because JavaScript might be disabled?
-Is it preferable to have code execute client-side versus server-side from a performance point of view?
-Does the content generated by the output of this function qualify as something you might want indexed by Search Engines?
Depending on the importance of the above criteria/questions, JavaScript might be disqualified.
From the points above, the common thing seems to be that choosing for JavaScript is more likely to lead to potentially undesirable side-effects.
The safest bet, from what I theorize, is therefore the server-side language, PHP.

Categories

Resources