Javascript 中 setInterval 函数怎么用?_WEB前端开发
在JavaScript中setInterval函数的作用是按照指定的周期时间来调用函数或计算表达,其语法为“setInterval(func,ms)”,返回值是一个ID,可以将这个ID传递给“clearInterval”函数来取消执行。
本文实例讲述了ES6 Generator基本使用方法。
分享给大家供大家参考,具体如下:
1.Generator介绍
先来一段Generator的基础代码
function* g(){ yield 100; yield 200; return 300; } let gg = g(); console.log(gg); // Object [Generator] {} console.log(gg.next()); // { value: 100, done: false } console.log(gg.next()); // { value: 200, done: false } console.log(gg.next()); // { value: 300, done: true } console.log(gg.next()); // { value: undefined, done: true }
首先我们看到:
Generator是由functinon*定义的,在generator内部可以使用yield
Generator不是函数,而是一个对象,并且在执行开始就进入暂停状态,而不是直接执行全部 *** 作
通过next()来执行下一步 *** 作,返回的都是{ value: xxx, done: xxx }这样的形式,value代表上一次 *** 作返回的值,done有两个值,一个是true,一个是false,表示整个流程是否全部结束。
ES6是什么前端技术?_WEB前端开发
ES6不是什么前端技术,ES6全称是ECMAScript 6,是正式发布的JavaScript语言的一种标准,该标准的目标是使得JavaScript语言可以用来编写复杂的大型应用程序,成为企业级开发语言。
2.Generator异步编程
generator是ES6中引入的异步解决方案,我们来看看它与promise处理异步的对比,来看它们的差异。
// 这里模拟了一个异步 *** 作 function asyncFunc(data) { return new Promise( resolve => { setTimeout( function() { resolve(data) },1000 ) }) }
promise的处理方式:
asyncFunc("abc").then( res => { console.log(res); // "abc" return asyncFunc("def") }).then( res => { console.log(res); // "def" return asyncFunc("ghi") }).then( res => { console.log(res); // "ghi" })
generator的处理方式:
function* g() { const r1 = yield asyncFunc("abc"); console.log(r1); // "abc" const r2 = yield asyncFunc("def"); console.log(r2); // "def" const r3 = yield asyncFunc("ghi"); console.log(r3); // "ghi" } let gg = g(); let r1 = gg.next(); r1.value.then(res => { let r2 = gg.next(res); r2.value.then(res => { let r3 = gg.next(res); r3.value.then(res => { gg.next(res) }) }) })
promise多次回调显得比较复杂,代码也不够简洁,generator在异步处理上看似同步的代码,实际是异步的 *** 作,唯一就是在处理上会相对复杂,如果只进行一次异步 *** 作,generator更合适。
3.yield和yield*
先来看两段代码
function* g1() { yield 100; yield g2(); return 400; } function* g2() { yield 200; yield 300; } let gg = g1(); console.log(gg.next()); // { value: 100, done: false } console.log(gg.next()); // { value: Object [Generator] {}, done: false } console.log(gg.next()); // { value: 400, done: true } console.log(gg.next()); // { value: undefined, done: true }
function* g1() { yield 100; yield* g2(); return 400; } function* g2() { yield 200; yield 300; } let gg = g1(); console.log(gg.next()); // { value: 100, done: false } console.log(gg.next()); // { value: 200, done: false } console.log(gg.next()); // { value: 300, done: false } console.log(gg.next()); // { value: 400, done: true }
yield对另一个generator不会进行遍历,返回的是迭代器对象,而yield*会对generator进行遍历迭代。
推荐教程:《JS教程》
以上就是ES6 Generator 基本使用的详细内容,更多请关注ki4网其它相关文章!
css3新增伪类有哪些_WEB前端开发
css快速入门:本文为大家介绍了css3中新增了哪些伪类的知识,希望可以帮助到大家。
css3新增伪类有:1、【p:first-of-type】;2、【p:last-of-type】;3、【p:only-of-type】。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)