当前位置:网站首页>Async await to achieve sleep waiting effect

Async await to achieve sleep waiting effect

2022-06-25 14:24:00 Fat goose 68

One 、 Problem description

At work , The vehicles in the map need to follow GPS Move , This requires that the center point of the map is centered on the car , Call directly setCenter Change the position of the center point , When the screen is big , The user thinks it is dazzling , The best way is to use flyto function , Realize the translation and smooth movement of the map .

But earlier versions API There is no flyto, The solution is to split the current center point to the final center point into several nodes , Then refresh quickly , Realization Small step run , Improve user experience .

problem : Make sure that the split middle point can start the next center point only after the page is refreshed

Two 、 How to ensure the refresh order

The idea is to use sleep Thought , After rendering the current center point , That is, the next rendering , There is a time to wait for rendering , So you can control the rhythm by yourself .

Why choose aysnc and await Well ?

Use aysnc and await , To make full use of js The advantages of single threading , When other callback functions need to set the center point again , It must be done with the current logic , Then the next center point change will be performed , To ensure the Sequence of the whole line

3、 ... and 、Vue Code case

<template>
  <div class>
    <div id="hmap" style="height: 200px;width: 200px;">
      {
   {msg}}
    </div>
  </div>
</template>

<script> export default {
       data () {
       return {
       msg: '' } }, mounted () {
       this.sleepAction() }, methods: {
       sleepAction () {
       const MAX = 4 const betweenTime = 2000 const that = this for (let i = 1; i <= MAX; i++) {
       // console.log(betweenTime * i) this.wait(betweenTime * i, function () {
       console.log('111111111111111', betweenTime * i) that.msg = betweenTime * i }) } }, sleep2 (time) {
       return new Promise((resolve) => {
       setTimeout(resolve, time) }) }, // async await async wait (time, fun) {
       await this.sleep2(time) if (fun) {
       fun() } } } } </script>

<style lang="scss" scoped></style>
原网站

版权声明
本文为[Fat goose 68]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200521565698.html