Edward Jackson

Edward Jackson

1594103515

JavaScript setTimeout() Function Tutorial with Examples

**setTimeout** is a native JavaScript function (although it can be used with a library such as jQuery, as we’ll see later on), which calls a function or executes a code snippet after a specified delay (in milliseconds). This might be useful if, for example, you wished to display a popup after a visitor has been browsing your page for a certain amount of time, or you want a short delay before removing a hover effect from an element (in case the user accidentally moused out).

**![set_timeout_2-01](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2015/08/1476830355set_timeout_2-01.png)**

This popular article was updated in 2020.

Basic setTimeout Example

To demonstrate the concept, the following demo displays a popup, two seconds after the button is clicked.

If you don’t see the popup open, please visit CodePen and run the demo there.

Syntax

From the MDN documentation, the syntax for setTimeout is as follows:

var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);

where:

  • timeoutID is a numerical ID, which can be used in conjunction with clearTimeout to cancel the timer.
  • scope refers to the Window interface or the WorkerGlobalScope interface.
  • function is the function to be executed after the timer expires.
  • code is an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires.
  • delay is the number of milliseconds by which the function call should be delayed. If omitted, this defaults to 0.
  • arg1, ..., argN are additional arguments passed to the function specified by function.

Note: the square brackets _[]_ denote optional parameters.

setTimeout vs window.setTimeout

You’ll notice that the syntax above uses scope.setTimeout. Why is this?

Well, when running code in the browser, scope would refer to the global window object. Both setTimeout and window.setTimeout refer to the same function, the only difference being that in the second statement we are referencing the setTimeout method as a property of the window object.

In my opinion, this adds complexity for little or no benefit. If you’ve defined an alternative setTimeout method which would be found and returned in priority in the scope chain, then you’ve probably got bigger problems to worry about.

For the purposes of this tutorial, I’ll omit window, but ultimately, which syntax you choose is up to you.

Examples of Use

setTimeout accepts a reference to a function as the first argument.

This can be the name of a function:

function greet(){
  alert('Howdy!');
}
setTimeout(greet, 2000);

A variable that refers to a function (a function expression):

const greet = function(){
  alert('Howdy!');
};
setTimeout(greet, 2000);

Or an anonymous function:

setTimeout(() => { alert('Howdy!'); }, 2000);

As noted above, it’s also possible to pass setTimeout a string of code for it to execute:

setTimeout('alert("Howdy!");', 2000);

However, this is not advisable for the following reasons:

  • It’s hard to read (and thus hard to maintain and/or debug).
  • It uses an implied eval, which is a potential security risk.
  • It’s slower than the alternatives, as it has to invoke the JS interpreter.

This Stack Overflow question offers more information on the above points.

Passing Parameters to setTimeout

In a basic scenario, the preferred, cross-browser way to pass parameters to a callback executed by setTimeout is by using an anonymous function as the first argument.

In the following example, we select a random animal from an animals array and pass this random animal as a parameter to a makeTalk function. The makeTalk function is then executed by setTimeout with a delay of one second:

function makeTalk(animal){
  const noises = {
    cat: 'purr',
    dog: 'woof',
    cow: 'moo',
    pig: 'oink',
  }

  console.log(`A ${animal} goes ${noises[animal]}.`);
}

function getRandom (arr) {
  return arr[Math.floor(Math.random()*arr.length)];
}

const animals = ['cat', 'dog', 'cow', 'pig'];
const randomAnimal = getRandom(animals);

setTimeout(() => {
  makeTalk(randomAnimal);
}, 1000);

Note: I’ve used a regular function (_getRandom_) to return a random element from an array. It would also be possible to write this as a function expression using an arrow function:

const getRandom = arr => arr[Math.floor(Math.random()*arr.length)];

We’ll get to arrow functions in the next section.

JS Bin

An Alternative Method

As can be seen from the syntax at the top of the article, there’s a second method of passing parameters to a callback executed by setTimeout. This involves listing any parameters after the delay.

With reference to our previous example, this would give us:

setTimeout(makeTalk, 1000, randomAnimal);

Unfortunately, this doesn’t work in IE9 or below, where the parameters come through as undefined. If you’re in the unenviable position of having to support IE9, there is a polyfill available on MDN.

The Problem with this

Code executed by setTimeout is run in a separate execution context to the function from which it was called. This is problematic when the context of the this keyword is important:

const dog = {
  sound: 'woof',
  bark() {
    console.log(`Rover says ${this.sound}!`);
  }
};

dog.bark();
// Outputs: Rover says woof!

setTimeout(dog.bark, 50);
// Outputs: Rover says undefined!

The reason for this output is that, in the first example, this points to the dog object, whilst in the second example this points to the global window object (which doesn’t have a sound property).

To counteract this problem, there are various measures …

#javascript #developer

What is GEEK

Buddha Community

JavaScript setTimeout() Function Tutorial with Examples
Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

Terry  Tremblay

Terry Tremblay

1602147513

Now Learn JavaScript Programming Language With Microsoft

icrosoft has released a new series of video tutorials on YouTube for novice programmers to get a hands-on renowned programming language — JavaScript.

This isn’t the first attempt by Microsoft to come up with video tutorials by beginner programmers. The company also has a series of YouTube tutorials on Python for beginners.

For JavaScript, Microsoft has launched a series of 51 videos as ‘Beginner’s Series to JavaScript,’ for young programmers, developers and coders who are interested in building browser applications using JavaScript. These video tutorials will also help programmers and coders to use relevant software development kits (SDKs) and JavaScript frameworks, such as Google’s Angular.


“Learning a new framework or development environment is made even more difficult when you don’t know the programming language,” stated on the Microsoft Developer channel on YouTube. “Fortunately, we’re here to help! We’ve created this series of videos to focus on the core concepts of JavaScript.”

It further stated — while the tutorials don’t cover every aspect of JavaScript, it indeed will help in building a foundation from which one can continue to grow. By the end of this series, Microsoft claims that the novice programmers will be able to work through tutorials, quick starts, books, and other resources, continuing to grow on their own.


#news #javascript #javascript tutorial #javascript tutorials #microsoft tutorials on javascript

wp codevo

wp codevo

1608042336

JavaScript Shopping Cart - Javascript Project for Beginners

https://youtu.be/5B5Hn9VvrVs

#shopping cart javascript #hopping cart with javascript #javascript shopping cart tutorial for beginners #javascript cart project #javascript tutorial #shopping cart

Madyson  Reilly

Madyson Reilly

1601069940

Function Expression vs Function Declaration in JavaScript

Function Expression vs Function Declaration in JavaScript.

It was until during one of the JavaScript mock interviews did I came across the term function expression.

The question was: What is the difference between these two syntax?

function x(){

}

let x = function(){

}

I was clueless for a moment. After thinking a little, I could only come up with: the second syntax invokes an _anonymous _function and is assigned to a variable.

I was alien to the term hoisting.

In this article, we will acquaint ourselves with three simple terms: function declaration,_ function expression, _and hoisting.

What is function declaration?

Function declaration is also known as _function statement. _It contains the name of the function, parameters, and a return statement. **Naming the function **is what sets function declaration apart. Parameters and return statement is optional.

Image for post

Function Declaration

What is function expression?

Function expression also has a name, parameters, and return statement. All of which are optional. The important thing to bear in mind is: the function here is _assigned _to a JavaScript variable.

Image for post

Function Expression

#function-expression #function-declaration #functions-in-javascript #coding #javascript #express

Lowa Alice

Lowa Alice

1624410000

JavaScript Factory Functions

JavaScript factory functions made simple.

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=jpegXpQpb3o&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=9
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #factory functions #functions #javascript factory functions