JavaScript series --JavaScript few odd tricks of prostitution implementation (a) short sleep function, get timestamp

I. Introduction

Something useful, but you may not know; some things you may have used, but you may not know principle.
There are many ways to achieve a purpose, the saying goes, all roads lead to Rome. Divergent what everyone's thinking and look to expand their knowledge.

 

Second, to achieve a short sleep function

sleep function is mainly used for delay in the implementation of many programming languages ​​have sleep function, but javascript function without this, we achieve this:

1, simple version

function sleep(sleepTime){
    for(var start = +new Date;+new Date - start<sleepTime;){} } var t1 = +new Date(); sleep(3000); var t2 = +new Date(); console.log(t2-t1);

Advantages: simple and crude, easy to understand.

Cons: really sleep, but the card is dead, cpu soar, accuracy allowed

 

2, promise version

// promise版本
function sleep(sleepTime){ return new Promise(resolve => setTimeout(resolve,sleepTime)); } var t1 = +new Date(); sleep(3000).then(()=>{ var t2 = +new Date(); console.log(t2-t1); }) 

Advantages: in fact, with the setTimeout, no blocking formation process, and the load will not cause performance problems.

Disadvantages: Although resolve nested callback, but still pretty, and asynchronous is not complete, the process stops executing.

 

3, generator version

// generotor版本
function sleep(sleepTime){ return function(cb){ setTimeout(cb.bind(this), sleepTime); } } function* genSleep(){ var t1 = +new Date(); yield sleep(3000); var t2 = +new Date(); console.log(t2-t1); } async(genSleep); function async(gen){ const iter = gen(); function nextStep(it){ if(it.done) return ; if (typeof it.value === "function") { it.value(function(ret) { nextStep(iter.next(ret)) }) } else { nextStep(iter.next(it.value)); } } nextStep(iter.next()); }

Pros: As with the advantages of promise, code more simple and clean.

Disadvantages: is executed every time next () is very troublesome, although  co (third-party packages) can be solved, but it is a multi-layer package, does not look good, the error must also  co  logic to deal with, of sorts.

co  reason why such a fire is not without reason, of course, not only to achieve sleep such a silly thing, but living through itgenerator/yield to achieve a very similar async/await effect! This really makes me Three Views doomed admiration.

const co = require("co")
function sleep(sleepTime) { return function(cb) { setTimeout(cb.bind(this), sleepTime) } } co(function*() { const t1 = +new Date() yield sleep(3000) const t2 = +new Date() console.log(t2 - t1) })

 

4, async / await release

function sleep(delay) {
  return new Promise(reslove => { setTimeout(reslove, delay) }) } !async function test() { const t1 = +new Date() await sleep(3000) const t2 = +new Date() console.log(t2 - t1) }()

Advantages: Promise and Generator with advantages. Async / Await Generator can be seen as syntactic sugar, async and Await more yield compared to * and semantics, various additional functions are flat, do not produce unwanted nested, refreshing code more readable.

Cons: compatibility problems ES7 grammar, and all the babel compatibility is not a problem

 

5, the open source version

In javascript elegant writing sleep is not equal to how elegant elegant, there are modules implemented in C ++: https://github.com/ErikDubbelboer/node-sleep

const sleep = require("sleep")

const t1 = +new Date() sleep.msleep(3000) const t2 = +new Date() console.log(t2 - t1)

Advantages: the ability to achieve finer time accuracy, and it seems that really sleep function, clear straightforward.
Disadvantages: the disadvantage of requiring the installation of this module Node-SLEEP .

 

Front-end knowledge : Async / Await is a way to write the most elegant front-end asynchronous

 

Second, elegant acquires a time stamp

To achieve the above  sleep functions, we can see that the code has  +new Date()usage time stamp is obtained, and this is just one of them, I said about the other two as well as the following  +new Date()principles.

1, Edition

var timestamp=new Date().getTime()

Advantages: universal, we all use this
shortcoming: There should be no bar

 

2, Advanced Edition

var timestamp = (new Date()).valueOf()

valueOf method returns the object's original value (Primitive, 'Null', 'Undefined', 'String', 'Boolean', 'Number' one of five basic types of data), may be strings, numbers, or the like bool value, see specific objects.

Pros: Description of the original developers have a specific cognitive value, it all themselves.
Cons: There should be no bar

 

3、Date.now()方法

Date.now()

Date.now() Method returns the number of milliseconds since January 1 1970 00:00:00 UTC to the current time. Type to Number. Because now () is Datea static function, it must be in the form of Date.now () to use.

Advantages: simple and clear.

Disadvantages: compatibility issues, ECMA-262 is standardized fifth edition.

Compatibility Compatibility code when not supported:

if (!Date.now) {
  Date.now = function now() { return new Date().getTime(); }; }

 

4, Redux

var timestamp = +new Date()

Pros: JavaScript for the implicit conversion of a firmer grasp of the performance
Disadvantages: There should be no bar

Let's analyze why + new Date () timestamp get?

That is an implicit conversion, in essence, is called valueOf () method.

 

note:

(1) One operator yuan +

One yuan  + operators convert their operands of  Number type and reverses its sign. Note that negative  +0 produces  -0a negative  -0 produce  +0.

+ New Date () corresponds ToNumber (new Date ())

 

(2)toString Returns a string representation of the object is used.

var obj = {};
console.log(obj.toString());//[object Object]

var arr = [];
console.log(arr.toString());//""空字符串 var date = new Date(); // Tue May 28 2019 22:05:58 GMT+0800 (中国标准时间) console.log(date.toString());//"Tue May 28 2019 22:05:58 GMT+0800 (中国标准时间)"

 

(3) valueOf () method returns the object's original value

valueOf method returns the object's original value (), may be strings, or boolean values ​​debriefing, see the specific object.

var obj = {
  name: "saucxs"
}
console.log(obj.valueOf()) //Object {name: "saucxs"}

var arr1 = [1,3] console.log(arr1.valueOf()) //[1,3] var date = new Date() console.log(date.valueOf())//1456638436303 // 如代码所示,三个不同的对象实例调用valueOf返回不同的数据

The original value refers to  'Null','Undefined','String','Boolean','Number','Symbol' one of the six basic data types, already mentioned this concept, here again affirms it.

 

Finally, the process of decomposition about them:+new Date():    

(1) the priority is higher than the new operator unary +, the process can be decomposed into: var time = new Date () ; + time

(2) according to the rules mentioned above corresponds to: ToNumber (time)

(3) time is a date object, according to the conversion rule ToNumber, it is equivalent to: ToNumber (ToPrimitive (time))

(4) According to the conversion rule ToPrimitive: ToNumber (time.valueOf ()), time.valueOf () is the original timestamp is worth to assumed time.valueOf () = 1503479124652

(5) so ToNumber (1,503,479,124,652) is the return value of this number 1503479124652.

Front-end knowledge: implicit conversion of Magical

 

Guess you like

Origin www.cnblogs.com/chengxs/p/10949075.html