setTimeout不可靠的修正办法及clearTimeout

javascript里的这两个定时器函数,大家一定耳熟能详:

setTimeout("函数()",毫秒)就是开启一个计时器,指定毫秒后执行该函数一次。
有关定时器,javascript还有另一个类似的函数,setInterval("函数()",毫秒)。不同的是,setInterval不是指定时间后执行一次该函数,而是每隔指定时间执行该函数,连续不断,直到clearInterval()。

问题是,在实际使用过程中,发现javascript的定时器很不靠谱。说好的多少多少时间后执行,但给人的感觉是忽快忽慢。明明指定3秒后执行,竟然5、6秒后才触发,或者不到1秒就触发了!

查阅资料,说是javascript为单线程,setTimeout之后,就注册了一个事件,进入排队,有空才执行,所以就慢了。大意如此。但快的情况呢?好像没说。

javascript引擎只有一个线程,迫使异步事件只能加入队列去等待执行。
在执行异步代码的时候,setTimeout 和setInterval 是有着本质区别的。
如果计时器被正在执行的代码阻塞了,它将会进入队列的尾部去等待执行直到下一次可能执行的时间出现(可能超过设定的延时时间)。
如果interval回调函数执行需要花很长时间的话(比指定的延时长),interval有可能没有延迟背靠背地执行。
上述这一切对于理解js引擎是如果工作的无疑是很重要的知识,尤其是大量的典型的异步事件发生时,对于构建一个高效的应用代码片段来说是一个非常有利的基础。

JavaScript的计时器的工作原理

那么能不能修正呢?受网上文章启发,可以采用读取时间来应对:

setTimeout的时候,记录当前时间戳
函数触发时,将时间戳与当前时间比较,看是否已经经过指定的毫秒数
时间未够,则继续setTimeout,步长可改为1秒
否则执行

<html>
<head>
</head>
<body>
<input type="button" value="开启" onclick="start()" />
</body>
</html>
<script type="text/javascript">
    var t;
    var marktime = 0;
    var offset = 3000;
    function start(){
        marktime = new Date().getTime();//1970年1月1日以来的毫秒数
        t = setTimeout("hi()",offset);//3000毫秒后触发
    }
    function hi(){
        if (new Date().getTime() - marktime < offset) {//时间未够
            t = setTimeout("hi()",1000);//一秒后再来看看
            return;
        }
        alert("Hello World!");
    }
</script>

以上方法可应对比指定时间快的情况。

至于clearTimeout,经测试

var t = setTimeout("hi()",1000);
clearTimeout();//不起任何作用
clearTimeout(t);//将计时器t消除

setTimeout的作用,就是注册一个计时器,计时器之间各自独立,不会覆盖和干扰;注册多少遍,就有多少个,执行指定函数后自己释放。所以每次setTimeout,应该获取返回值,以便操控:

var t = setTimeout("hi()",1000);
clearTimeout(t);//将计时器t消除
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/goods.js"></script> <style> .goods-list { width: 100%; height: 300px; border: 1px solid #000; overflow: auto; } .clear::after { content: ""; display: block; clear: both; visibility: hidden; height: 0; } .goods { width: 150px; height: 200px; float: left; overflow: hidden; margin: 10px; } .goods>img { width: 100%; } .goods * { pointer-events: none; } table { width: 100%; border-collapse: collapse; } th, td { /* border: 1px solid #000; */ text-align: center; } .step-num>button { width: 30px; height: 30px; font-size: 25px; line-height: 25px; border-radius: 1; } .step-num>input { width: 50px; height: 25px; font-size: 20px; position: relative; top: -2px; border: 1px solid #000; border-left: none; border-right: none; outline: none; text-align: center; } </style> </head> <body> <div class="goods-list clear"></div> <table> <thead> <tr> <th style="width: 60px"><input type="checkbox" id="all" />全选</th> <th style="width: 80px">商品图</th> <th style="width: 300px">商品信息</th> <th>类型</th> <th>单价</th> <th style="width: 120px">数量</th> <th>合计</th> <th>操作 <button class="alldelete">删除</button></th> </tr> </thead> <tbody></tbody> </table> <img class="view-img" style=" display: none; position: fixed; left: 0; top: 0; bottom: 0; right: 0; margin: auto; " /> <script> var goodsList, tbody, id, all, viewImg, alldelete; var shoppingList = []; init(); function init() { goodsList = document.querySelector('.goods-list'); viewImg = document.querySelector('.view-img'); tbody = document.querySelector('tbody'); all = document.querySelector('#all'); alldelete = document.querySelector('.alldelete'); goodsList.innerHTML = list.map((item) => createGoods(item)).join(""); goodsList.addEventListener('click', addGoodsHandler); tbody.addEventListener('input', inputHandler); tbody.addEventListener('click', tbodyClickHandler); all.addEventListener('change', allChangeHandler); viewImg.addEventListener('click', (e) => (viewImg.style.display = 'none')); alldelete.addEventListener('click', allDeleteHandler); } function allDeleteHandler(e) { shoppingList = shoppingList.filter((item) => !item.checked); render(); } function allChangeHandler(e) { shoppingList.forEach((item) => { item.checked = e.target.checked; }); render(); } function createGoods(item) { return ` <div class='goods' id=${item.proid}> <img src=${item.img1}> <div> <span>${item.proname}</span> </div> </div> `; } function addGoodsHandler(e) { if (e.target.className !== 'goods') return; const id = e.target.id; const shopItem = shoppingList.find((item) => item.id === id); if (!shopItem) { const item = list.find((item) => item.proid == id); const data = { id: item.proid, checked: false, img: item.img1, indo: item.desc, type: item.category, pruce: item.originprice, num: 1, total: item.originprice, }; shoppingList.push(data); } else { shopItem.num++; shopItem.total = shopItem.price * shopItem.num; } render(); } function render() { all.checked = shoppingList.every((item) => item.checked); tbody.innerHTML = shoppingList.map((item) => { return `<tr data=${item.id} > <td><input type="checkbox" class='select' ${item.checked ? "checked" : "" }/></td> <td><img src='${item.img}' width='80'/></td> <td><div style='height:70px;overflow:hidden'>${item.info }</div></td> <td>${item.type}</td> <td>¥${item.price.toFixed(2)}</td> <td class='step-num'><button class='subtraction' ${item.num === 1 ? "disabled" : "" }>-</button><input class='step' type='text' value='${item.num }'/><button class='add'>+</button></td> <td>¥${item.total.toFixed(2)}</td> <td><button class='view'>查看</button><button class='delete'>删除</button></td> </tr>` }).join(''); } function tbodyClickHandler(e) { if (!['BUTTON', 'INPUT'].includes(e.target.nodeName)) return; const id = e.target.parentElement.parentElement.getAttribute('data'); const item = shoppingList.find((item) => item.id == id); switch (e.target.className) { case 'subtraction': if (item.num === 1) return; item.num--; item.total = item.price * item.num; break; case 'add': item.num++; item.total = item.price * item.num; break; case 'select': item.checked = e.target.checked; break; case 'view': viewImg.src = item.img; viewImg.style.display = 'block'; return; case 'delete': shoppingList = shoppingList.filter((item) => item.id != id); break; default: return; } render(); } function inputHandler(e) { if (e.target.className !== 'step' || id) return; id = setTimeout(() => { e.target.value = parseInt(e.target.value) || '1'; const proid = e.target.parentElement.parentElement.getAttribute('data'); const item = shoppingList.find((item) => item.id == proid); item.num = Number(e.target.value); item.total = item.price * item.num; clearTimeout(id); id = undefined; render(); }, 1000); } </script> </body> </html>
07-26
<template> <div> <el-dialog :visible.sync="dialogVisible" width="70%" :show-close="false" :close-on-click-modal="false" append-to-body @open="handleOpen" @close="handleClose" > <template slot="title"> <div style="text-align: center; font-size: 22px;"> {{ title }} </div> </template> <el-form :model="detailForm" label-width="130px" v-loading="loading"> <el-row> <el-col :span="8"> <el-form-item label="日期:"> <el-input readonly v-model="detailForm.recordDate"></el-input> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="班别:"> <el-input readonly v-model="detailForm.workClass"></el-input> </el-form-item> </el-col> </el-row> <el-form-item label="异常机况:"> <el-table :data="eqpList" style="width: 100%" id="eqpTable"> <el-table-column prop="area" label="Area"></el-table-column> <el-table-column prop="eqpId" label="Eqp Id"></el-table-column> <el-table-column prop="eqpName" label="Eqp Name"></el-table-column> <el-table-column prop="eqpStatus" label="Eqp Status"></el-table-column> <el-table-column prop="eqpHour" label="Hour"></el-table-column> <el-table-column prop="eqpUser" label="User"></el-table-column> <el-table-column prop="comments" label="Comment"></el-table-column> </el-table> <el-input type="textarea" v-model="detailForm.abnormal" :autosize="{ minRows: 2 }" placeholder="请输入异常机况 或 选中粘贴图片" @paste="handlePaste($event, abnormalImageRef)" :readonly="!detailForm.editAuth" ></el-input> <el-upload ref="abnormalImageRef" v-model="detailForm.abnormalImageList" action="#" :http-request="handleHttpUpload" list-type="picture-card" :before-upload="beforeUpload" :on-success="() => uploadSuccess('abnormalImageList')" :on-error="uploadError" :accept="fileType.join(',')" :on-preview="handlePreview" :disabled="!detailForm.editAuth" > <i class="el-icon-plus"></i> </el-upload> </el-form-item> <el-form-item label="产片:"> <el-table :data="lotList" style="width: 100%" id="lotTable"> <el-table-column prop="eqp" label="机台"></el-table-column> <el-table-column prop="priority" label="Priority"></el-table-column> <el-table-column prop="lotId" label="Lot ID"></el-table-column> <el-table-column prop="maskTitle" label="Mask Title"></el-table-column> <el-table-column prop="dueDay" label="Due Day"></el-table-column> </el-table> <el-input type="textarea" v-model="detailForm.product" :autosize="{ minRows: 2 }" placeholder="请输入产片 或 选中粘贴图片" @paste="handlePaste($event, productImageRef)" :readonly="!detailForm.editAuth" ></el-input> <el-upload ref="productImageRef" v-model="detailForm.productImageList" action="#" :http-request="handleHttpUpload" list-type="picture-card" :before-upload="beforeUpload" :on-success="() => uploadSuccess('productImageList')" :on-error="uploadError" :accept="fileType.join(',')" :on-preview="handlePreview" :disabled="!detailForm.editAuth" > <i class="el-icon-plus"></i> </el-upload> </el-form-item> <el-form-item label="工程师交接事项:"> <el-input type="textarea" v-model="detailForm.engHandover" :autosize="{ minRows: 2 }" placeholder="请输入工程师交接事项 或 选中粘贴图片" @paste="handlePaste($event, engHandoverImageRef)" :readonly="!detailForm.editAuth" ></el-input> <el-upload ref="engHandoverImageRef" v-model="detailForm.engHandoverImageList" action="#" :http-request="handleHttpUpload" list-type="picture-card" :before-upload="beforeUpload" :on-success="() => uploadSuccess('engHandoverImageList')" :on-error="uploadError" :accept="fileType.join(',')" :on-preview="handlePreview" :disabled="!detailForm.editAuth" > <i class="el-icon-plus"></i> </el-upload> </el-form-item> <el-form-item label="课长:" v-if="detailForm.managerName !== null"> <el-input v-model="detailForm.managerName" readonly></el-input> </el-form-item> <el-form-item label="接班人:" v-if="detailForm.assigneeName !== null"> <el-input type="textarea" v-model="detailForm.assigneeName" readonly autosize></el-input> </el-form-item> </el-form> <template slot="footer"> <el-button type="primary" @click="save" v-if="detailForm.editAuth">保存</el-button> <el-button @click="closeDialog">取消</el-button> <el-button type="primary" @click="submit" v-if="detailForm.submitAuth">提交</el-button> <el-button type="primary" @click="audit" v-if="detailForm.auditAuth">审核</el-button> <el-button type="primary" @click="assign" v-if="detailForm.assignAuth">签核</el-button> </template> </el-dialog> <el-dialog :visible.sync="previewVisible" :show-close="false"> <img width="100%" :src="previewImageUrl" alt="Preview Image"/> </el-dialog> </div> </template> <script> import { getJournalForEdit, saveJournal, submitJournal, auditJournal, assignJournal, clearEditUser } from '@/api/mfgLog/area'; import request from '@/utils/request'; import {Message, MessageBox } from "element-ui"; import dayjs from 'dayjs'; import { getToken } from '@/utils/auth' export default { data() { return { loading: false, dialogVisible: false, title: '光罩厂制造部站点交接记录簿', fileType: ['image/jpeg', 'image/png', 'image/gif'], abnormalImageRef: null, engHandoverImageRef: null, productImageRef: null, previewVisible: false, previewImageUrl: '', detailForm: { recordDate: '', workClass: '', workArea: '', abnormal: '', lotList: [], eqpList: [], abnormalImage: '', abnormalImageList: [], product: '', productImage: '', productImageList: [], engHandover: '', engHandoverImage: '', engHandoverImageList: [], managerName: '', assigneeName: '', editAuth: false, submitAuth: false, auditAuth: false, assignAuth: false, id: '' }, timer: null }; }, mounted() { // 监听事件以重置计时器 window.addEventListener('keydown', this.resetTimer); window.addEventListener('mousemove', this.resetTimer); window.addEventListener('mouseenter', this.resetTimer); // 浏览器关闭事件 window.addEventListener('beforeunload', (e) => { this.userInactive(); }); }, beforeDestroy() { // 清除事件监听和计时器 window.removeEventListener('keydown', this.resetTimer); window.removeEventListener('mousemove', this.resetTimer); window.removeEventListener('mouseenter', this.resetTimer); clearTimeout(this.timer); }, methods: { handleOpen() { this.resetTimer(); }, handleClose() { clearTimeout(this.timer); }, resetTimer() { // 用户进行了操作,重置计时器 if (this.timer) { clearTimeout(this.timer); } this.startTimer(); }, startTimer() { // 设置5分钟后的无操作处理 this.timer = setTimeout(() => { // 用户5分钟内无操作,执行相关逻辑 if (this.dialogVisible) { this.userInactive(); } }, 5 * 60 * 1000); }, userInactive() { // 用户处于非活跃状态的逻辑处理 if (this.detailForm.editAuth) { this.save(); } this.closeDialog(); }, showDialog(row) { this.loading = true; getJournalForEdit(row).then(res => { Object.assign(this.detailForm, res.data); // 显示提示信息 if (!this.detailForm.editAuth && !this.detailForm.assignAuth && this.detailForm.editUser) { Message.warning({ message: "当前日志正在被 " + this.detailForm.editUserName + " 编辑", position: 'top', // 确保消息显示在页面顶部 duration: 5000 // 消息显示时间为 5 秒 }); return 0; } this.detailForm.abnormalImageList = []; if (this.detailForm.abnormalImage?.length > 0) { let abnormalList = this.detailForm.abnormalImage.split(","); for (let index in abnormalList) { this.detailForm.abnormalImageList.push({ url: abnormalList[index] }); } } this.detailForm.productImageList = []; if (this.detailForm.productImage?.length > 0) { let productList = this.detailForm.productImage.split(","); for (let index in productList) { this.detailForm.productImageList.push({ url: productList[index] }); } } this.detailForm.engHandoverImageList = []; if (this.detailForm.engHandoverImage?.length > 0) { let engHandoverList = this.detailForm.engHandoverImage?.split(","); for (let index in engHandoverList) { this.detailForm.engHandoverImageList.push({ url: engHandoverList[index] }); } } if (this.detailForm.lotList && Array.isArray(this.detailForm.lotList)) { this.lotList = this.detailForm.lotList; } else { this.lotList = []; // 否则初始化为空数组 } if (this.detailForm.eqpList && Array.isArray(this.detailForm.eqpList)) { this.eqpList = this.detailForm.eqpList; } else { this.eqpList = []; // 否则初始化为空数组 } this.title = "光罩厂制造部 " + this.detailForm.workArea + " 站点交接记录簿"; // 判断当前时间是否允许提交/审核日志 if (this.detailForm.submitAuth || this.detailForm.auditAuth) { // 白班18点30分之前允许提交和审核 let authTime = this.detailForm.recordDate + " 18:30:00"; if ('N' == this.detailForm.workClass.substring(0, 1)) { // 晚班06点30分之前允许提交和审核 authTime = dayjs(this.detailForm.recordDate).add(1, 'day').format("YYYY-MM-DD") + " 06:30:00"; } if (dayjs().isBefore(dayjs(authTime))) { this.detailForm.submitAuth = false; this.detailForm.auditAuth = false; } } // 父系统页面打开遮罩 window.parent.postMessage("open", '*'); this.dialogVisible = true; // 设置初始计时器 this.loading = false; }).catch(error => { console.log(error); this.loading = false; }); }, closeDialog() { clearEditUser({ id: this.detailForm.id }).catch(error => { Message.error(error.msg ? error.msg : error); }); this.$emit('close'); // 父系统页面关闭遮罩 window.parent.postMessage("close", '*'); this.dialogVisible = false; }, save() { this.detailForm.abnormalImage = this.detailForm.abnormalImageList.map(item => item.url).join(","); this.detailForm.productImage = this.detailForm.productImageList.map(item => item.url).join(","); this.detailForm.engHandoverImage = this.detailForm.engHandoverImageList.map(item => item.url).join(","); this.loading = true; saveJournal(this.detailForm).then(res => { this.loading = false; Message.success("保存成功"); this.closeDialog(); }).catch(error => { this.loading = false; }); }, submit() { MessageBox.confirm("确认要提交吗?", "提示", { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', }).then(res => { this.detailForm.abnormalImage = this.detailForm.abnormalImageList.map(item => item.url).join(","); this.detailForm.productImage = this.detailForm.productImageList.map(item => item.url).join(","); this.detailForm.engHandoverImage = this.detailForm.engHandoverImageList.map(item => item.url).join(","); this.loading = true; submitJournal(this.detailForm).then(res => { this.loading = false; Message.success("提交成功"); this.closeDialog(); }).catch(error => { this.loading = false; Message.error(error.msg ? error.msg : error); }); }).catch(error => { console.log(error); }); }, audit() { MessageBox.confirm("确认要提交审核吗?", "提示", { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', }).then(res => { this.detailForm.abnormalImage = this.detailForm.abnormalImageList.map(item => item.url).join(","); this.detailForm.productImage = this.detailForm.productImageList.map(item => item.url).join(","); this.detailForm.engHandoverImage = this.detailForm.engHandoverImageList.map(item => item.url).join(","); this.detailForm.lotList = this.detailForm.lotList this.detailForm.eqpList = this.detailForm.eqpList this.loading = true; auditJournal(this.detailForm).then(res => { this.loading = false; Message.success("审核成功"); this.closeDialog(); }).catch(error => { this.loading = false; Message.error(error.msg ? error.msg : error); }); }).catch(error => { console.log(error); }); }, assign() { MessageBox.confirm("确认要签核吗?", "提示", { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', }).then(res => { this.loading = true; assignJournal({ id: this.detailForm.id }).then(res => { this.loading = false; Message.success("签核成功"); this.closeDialog(); }).catch(error => { this.loading = false; Message.error(error.msg ? error.msg : error); }); }).catch(error => { console.log(error); }); }, handleHttpUpload(options) { return process.env.VUE_APP_BASE_API + '/viewException/uploadImage' }, headers(){ return { "Authorization": 'Bearer ' + getToken() } }, beforeUpload(rawFile) { const imgType = this.fileType.includes(rawFile.type); if (!imgType) { Message.warning({ title: '温馨提示', message: '上传图片符合所需的格式!', }); } return imgType; }, uploadSuccess(imageListName) { Message.success({ title: '温馨提示', message: '图片上传成功!', }); this.detailForm[imageListName].forEach(item => { if (item.url.indexOf("/api/") < 0) item.url = item.response.url; }); }, uploadError() { Message.error({ title: '温馨提示', message: '图片上传失败,请您重新上传!', }); }, handlePaste(event, uploadRef) { const items = (event.clipboardData || window.clipboardData).items; let file = null; if (!items || items.length === 0) { Message.error("当前浏览器支持粘贴板"); return; } // 搜索剪切板items for (let i = 0; i < items.length; i++) { if (items[i].type.indexOf("image") !== -1) { file = items[i].getAsFile(); break; } } if (!file) { return; } uploadRef.handleStart(file); // 将粘贴过来的图片加入预上传队列 uploadRef.submit(); // 提交图片上传队列 }, handlePreview(file) { this.previewImageUrl = file.url; this.previewVisible = true; } } }; </script> <style scoped> .layout-padding-custom { padding: 20px; } .border-vxe-table { margin-top: 20px; } </style> 报错vue.runtime.esm.js:620 [Vue warn]: Error in v-on handler: "TypeError: reqs[uid].abort is not a function" found in ---> <ElUploadList> at packages/upload/src/upload-list.vue <ElUpload> at packages/upload/src/index.vue <ElFormItem> at packages/form/src/form-item.vue <ElForm> at packages/form/src/form.vue <ElDialog> at packages/dialog/src/component.vue <Detail> at src/views/mfgLog/area/detail.vue <Index> at src/views/mfgLog/area/index.vue <AppMain> at src/layout/components/AppMain.vue <Layout> at src/layout/index.vue <App> at src/App.vue <Root> warn @ vue.runtime.esm.js:620 logError @ vue.runtime.esm.js:1892 globalHandleError @ vue.runtime.esm.js:1887 handleError @ vue.runtime.esm.js:1847 invokeWithErrorHandling @ vue.runtime.esm.js:1870 invoker @ vue.runtime.esm.js:2187 invokeWithErrorHandling @ vue.runtime.esm.js:1862 Vue.$emit @ vue.runtime.esm.js:3897 click @ element-ui.common.js:28831 invokeWithErrorHandling @ vue.runtime.esm.js:1862 invoker @ vue.runtime.esm.js:2187 original._wrapper @ vue.runtime.esm.js:6951 vue.runtime.esm.js:1896 TypeError: reqs[uid].abort is not a function at VueComponent.abort (element-ui.common.js:29351:21) at VueComponent.abort (element-ui.common.js:29717:34) at doRemove (element-ui.common.js:29688:16) at VueComponent.handleRemove (element-ui.common.js:29695:9) at invokeWithErrorHandling (vue.runtime.esm.js:1862:26) at Proxy.invoker (vue.runtime.esm.js:2187:14) at invokeWithErrorHandling (vue.runtime.esm.js:1862:26) at Vue.$emit (vue.runtime.esm.js:3897:9) at click (element-ui.common.js:28831:37) at invokeWithErrorHandling (vue.runtime.esm.js:1862:26)
最新发布
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值