In the front-end, timing is a very important knowledge point, and scheduled tasks are everywhere. The following article will summarize the three types of scheduled tasks that the front-end must master. I hope it will be helpful to you!
Scheduled tasks, a simple understanding is what to do after how long. What to do at regular intervals. Have you felt it? In fact, scheduled tasks are a ubiquitous thing.
For example, the flash sale countdown of the e-commerce platform will be executed every second, giving you A sense of urgency that is about to end;For exampleWhen we buy a ticket from 12306, the countdown on the payment page will tell you every second that if your order is not paid, the ticket will no longer belong;For example The product staff told us that at 12 o'clock every night, the data of table A must be backed up; For example, 1 minute after the page addition is completed, it will automatically jump to another page.
For another example, HR tells you to go to the conference room at 3 pm because there are important things to discuss; for example, you have to start work at 9 o'clock every day, and it will not work if you are late; for example, you start work early at 9:30 every day. Yes, the team leader is always there no matter what. If you don’t go, he will look down on you; for example, your salary will be paid on the 15th of every month, and not a day earlier; for example, you will not retire until you are 65 years old, but he doesn’t care if you are 35 years old. No matter what you do when you are 65 years old, it doesn’t matter whether your company thinks that you are an older coder at 35 years old. These are all timers. They will tell you at a fixed time that you must do it. There are codes in the program to control it. There is an invisible hand in life. You can’t see it, but it does. Control you.
The usage scenario of setTimeout stipulates how long it will take to execute something, and it will only be executed once. Today we simply implement a scenario that stipulates that certain things should not be loaded after the page is loaded, in order to reduce the content loaded for the first time and reduce the pressure of first-screen rendering. When the first screen component is loaded 500 milliseconds, we load some additional things.Take vue as an example. For example, the first screen is placed under a.vue. We know that the mounted life cycle can indicate that the DOM of this component has been loaded, but the component has been loaded, which does not represent images and requests. The rendering has been completed, so we have reserved 500 milliseconds. The code is as follows:
。。。 // 表示a.vue其余代码 mounted() { let timeout1 = setTimeout(() => { // 需要延迟做的事情 // 并且延迟完毕要清除setTimeout timeout1 = null; window.clearTimeout(timeout1); }, 500) },
Many times we do not recommend using setInterval , the reason is mentioned below. Although setTimeout is executed once, if it is executed again after execution, it will become multiple executions.For example, we implement an accumulator that starts accumulating from 0. The super cool code is like the following. Isn’t it great? It’s not like my code can’t run. Even if the code can’t run, I can You can run.
var num = 0; setTimeout(() => { num += 1; setTimeout(() => { num += 1; setTimeout(() => { num += 1; ...... setTimeout(() => { num += 1; }, 970) }, 970) }, 970) }, 970)
var num = 0; function timeoutFn() { setTimeout(() => { num += 1; timeoutFn(); }, 970) console.log('经海路大白狗看一下num吧', num); } timeoutFn();
Have you noticed a feature of Brother Gou’s blog? I constantly emphasize project scenarios. Project scenarios hope that you will not isolate knowledge points. Knowledge points must be used in actual combat. We No matter how much you learn and develop knowledge points, you will eventually go to a company to earn wages.
var num = 0; setInterval(() => { if (num >= 100) { num = 0; } num += 13; }, 970)
所以我们会经常发现一个问题,例如轮播图正在准时3秒动一次,然后浏览器被切走了,等你隔一段时间回来后呢,轮播图就像疯了一样的转动,然后再继续恢复为3秒一动;又或者是在IOS还是什么环境下来着,我记得当时是做一个倒计时的功能。当浏览器切走之前还剩12分钟,等浏览器切走之后呢,倒计时就不动了,等过了2分钟再切回来的时候,发现还是12分钟,又开始倒计时。
其实这个时候可以检测当前浏览器是否处于用户眼前(或者说是否被切走了),用这个代码来判断:
var countSecondFn = null; function goOnCount() { countSecondFn = setInterval(() => { // 任务执行 }) } document.addEventListener('visibilitychange',function(){ if(document.visibilityState=='hidden'){ window.clearInterval(countSecondFn); countSecondFn = null; }else if(document.visibilityState=='visible'){ goOnCount(); } });
所以很多时候,我们更希望用setTimeout的递归来替换掉setInterval的执行,减少更多的问题。
node-schedule目前主要用于node服务端,例如我们的一些页面,数据是配置出来的,那么就没有必要每次都去请求数据库,再返回给前端,可以定时一下,几分钟发送一次请求即可;再比如我们每次升级上线,为了保证一个良好的性能,HTML可能会部署在服务端,而静态资源则部署在另外的服务器。这样静态资源从v1.0升级到v1.1,则可以定时的去获取配置平台的版本号,然后动态拼接到HTML页面上,以保证可以每次升级拿到最新的静态资源。
但node-schedule和setInterval有本质上的区别。node-schedule更强调哪一天哪个小时,哪一分钟,哪一秒钟准确的去执行。就像我们经常被告知你明天早上9点去做一件什么事情,每天晚上9点你才可以下班。这样的场景,恐怕setInterval不能够胜任了。
例如每到10分(3点10分、8点10分。。。12点10分)的时候,我们去请求一下数据,第一次请求到的数据进行缓存处理,再次请求到的数据与老数据进行对比,如果无更新则继续用缓存数据,如果有更新则利用新数据。
const schedule = require('node-schedule'); let job = schedule.scheduleJob('* 10 * * * *', () => { axios(url, data, (res) => { // 与缓存数据对比 // 后者再犯个懒,不对比,每次都用新数据,请求异常了再用缓存数据 }) });
上一段代码中的 * 10 * * * * 呢,就是所谓node-schedule的定时钥匙,这6个星号从左到右表示:秒 分 小时 天 月 年 ,这样看是不是就更明白他的准确性和与setInterval的区别了。
竟然这个Corn定时钥匙如此准确,规定了哪一分钟那一秒钟去执行,去取数据,比如你写的是每分钟的第10秒去获取,这本没有问题。比如全公司都公用一个配置平台呢,你每分钟的第10秒去获取,那比如你这个项目用到了N台机器呢,这N台是否要都是每分钟的第10秒去获取?那如果全公司的N个业务系统都这么写呢,会有什么问题呢?哈哈,如果听明白了狗哥的意思,欢迎和狗哥交流。
其实我觉得对于自学前端,急于找到前端开发工作的人,没有太大必要去学习node服务端知识。你基本把纯前端的知识学到位已经很不容易了。但如果有时间,还是建议简单学习一下,哪怕只是搭个koa的架子,练习着写一下接口数据格式。一旦自己练习写过接口数据,自己再从前端发送ajax调用一下,我相信你将会有一个更全面的对开发项目的认知,在你遇到问题的时候,有更多的解决思路。
但如果你没有学透,千万别在简历上写你精通node服务端,也别给自己挖坑说自己做过。你不说他们也不会问,这不丢人,放心吧。
狗哥觉得其实即便你做了开发,也不应该生活中只有开发,我们努力工作是为了生活,为了更好的生活,所以狗哥更偏向于基于故事讲基础知识点,也更喜欢着力于知识点冒出个小故事(这句话换成抓手咋说?)。
慢慢的,习惯了开发中的定时任务,我们清楚的知道几秒后该让网页执行一件什么事,每天几点该执行一件什么事,可能觉得已经能够胜任工作了,但久而久之,你到了一定的时刻就必须得离开学校,赖在那里也没有用,到了一定的时机,你就需要结婚生子去面对。没人有强拉着你9点前必须到公司,但你知道9点前不到不行。老板告诉你这个东西下班就得做出来,你不做出来也行啊,但你知道你必须做出来。
Life is like a big timer, and inside the big timer are small timers that are closely linked together. They are invisible but seem to be tangible, until the eternity you don’t know.
[Recommended learning: javascript video tutorial]
The above is the detailed content of [Summary] 3 types of scheduled tasks that the front-end must master. For more information, please follow other related articles on the PHP Chinese website!