SetTimeout grammar:

var timeoutId = scope.setTimeout(function[, delay, param1, param2....] ); var timeoutId = scope.setTimeout(function[, delay]); var timeoutId = scope.setTimeout(code[, delay]);Copy the code

setTimeoutKey points:

The first argument to setTimeout can be a function or a string containing Javascript code (analogous to using strings in eval()).

// Method 1: General writing style
setTimeout(function(){
	console.log(a)
},1000)

// Method 2: A string can also be used
setTimeout("console.log(a)".1000);
Copy the code

However, mode 2 is not recommended, either for code readability, MDN’s official explanation-security reasons, or for performance reasons in older browsers.


setTimeoutPoint 2:

Javascript is a single-threaded interpreter, so only one piece of code can be executed at a time, so there are queues of Javascript tasks that execute in the order in which they are queued. The second parameter of setTimeout, -delay, tells Javascript how long it will take to add the current task to the queue.

If this parameter is omitted, delay takes the default value 0. The actual delay may be longer than the delay value (usually due to function nesting (at a certain level of nesting), or due to the blocking of setInterval callbacks that have already been executed).

Delay is greater than or equal to 4ms, as specified in the HTML5 Spec, even if you set delay to 0


setTimeoutPoint three:

SetTimeout Optional arguments: Additional arguments that will be passed as arguments to the function or execution string (code in the setTimeout argument) once the timer is executed.

setTimeout(function(param1,param2){
	console.log(param1)   //a
	console.log(param2)   //b
},1000.'a'.'b')
Copy the code
function timeout(ms) {
	return new Promise((resolve, reject) = > {
		setTimeout(resolve, ms, 'finish');
	});
}

timeout(100).then((value) = > {
	console.log(value);		//finish
});
Copy the code

setTimeoutPoint four:

SetTimeout is executed in a global scope, so this in a Function refers to a window object (in general, excluding ES6 arrow functions, function.prototype.bind (), closure override chain objects… Other ways to change scope, etc.)

var obj = {
	timer:function(){
		setTimeout(function(){
			console.log(this= =window)     //true
		})
	}
}
obj.timer()
Copy the code

Although there are quite a few books/documents that say strictly this is undefined.

BUT, in strict mode, this in the callback function of setTimeout() still points to the window object by default, not undefined

"use strict";
setTimeout(function(){
	console.log(this= =window)    //true
})
Copy the code