JavaScript手写原生任务定时器实现详解

作者:小括号时间:2026-10-24 23:51:45浏览:496

本文介绍如何在JavaScript中通过原生代码实现一个轻量级的定时任务调度器。该方案无需依赖第三方插件,支持启动、停止、添加及清除定时任务。通过定义包含执行函数、参数及时间表达式(年、月、日、时、分、秒)的对象,利用setInterval实现周期性调度,满足前端复杂业务对定时执行的需求。

功能介绍

功能介绍

定时器背景与需求

定时器旨在特定时间点执行预定任务。现代应用程序的复杂性已远超简单的增删改查操作,任务定时调度与执行已成为标配需求。基于时间表达式进行调度和执行的任务被称为定时任务,许多业务场景的实现都依赖于此类功能。

JavaScript实现方案

在JavaScript中实现定时任务并不复杂,开发者既可选用现有插件,也可自行编写简易的定时任务模块。本文旨在提供一个基于的循环定时任务实现方案,具备启动、停止、添加、清除定时任务以及执行定时器方法等功能。

实现调用演示

实现调用演示

方法定义

1.定义两个方法 有参和无参

function a1(value = "") {
            console.log("定时任务被调用了 携带的参数==>>", value)
        }

        function a2() {
            console.log("定时任务被调用了 我是无参数")
        }

定时任务实现

2. 实现定时任务

let daily_time = {
            func: a1,
            parm: "我是每秒",
            year: "*",
            month: "*",
            date: "*",
            hours: "*",
            minutes: "*",
            seconds: "*"
        }
        let monthly_transaction = {
            func: a2,
            parm: null,
            year: "*",
            month: "*",
            date: "*",
            hours: "*",
            minutes: "1",
            seconds: "*"
        }
        
        let monthly_summary = {
            func: a1,
            parm: "我是每小时 1分 1秒",
            year: "*",
            month: "*",
            date: "*",
            hours: "*",
            minutes: "1",
            seconds: "1"
        }
        addTimer(daily_time)
        addTimer(monthly_transaction)
        addTimer(monthly_summary)
        startTimer()

代码使用指南

创建定时任务js 代码文件 复制使用即可

文件说明

bg-timer.js

// 缓存定时任务
// {
//     func 方法名
//  parm 方法参数

//     year 年
//     month 月
//  date 日
//     hours 时
//     minutes 分
//     seconds 秒
// }
//  * 表示每刻都执行  数字 表示定时这个时间执行

/**
* 每年 1月1日1时1分1秒
* year *
* month 1
* date 1
* hours 1
* minutes 1
* seconds 1
*/

/**
* 每年每月每日每时1分每秒
* year *
* month *
* date *
* hours *
* minutes 1
* seconds *
*/

/**
* 每秒
* year *
* month *
* date *
* hours *
* minutes *
* seconds *
*/

var timer_list = []
var is_timer = null


// 启动
function startTimer() {
    console.log("启动定时任务")
    if (!is_timer) {
        timeoutFunc()
    }
}

// 停止
function stopTimer() {
    console.log("停止定时任务")
    if (is_timer) {
        clearInterval(is_timer);
        is_timer = null
    }
}

// 清除定时任务
function cleanTimer() {
    stopTimer()
    timer_list = []
}


// 添加定时任务
function addTimer(item = {}) {
    let n = {
        "func": item.func || null,
        "parm": item.parm || null,
        "year": item.year || "*",
        "month": item.month || "*",
        "date": item.date || "*",
        "hours": item.hours || "*",
        "minutes": item.minutes || "*",
        "seconds": item.seconds || "*"
    }
    timer_list.push(n)
}


function timeoutFunc() {
    if (is_timer) {
        return
    }
    is_timer = setInterval(function() {
        let da = new Date()
        let fullYear = (da.getFullYear()).toString()
        let month = (da.getMonth()).toString()
        let dat = (da.getDate()).toString()
        let hours = (da.getHours()).toString()
        let minutes = (da.getMinutes()).toString()
        let seconds = (da.getSeconds()).toString()

        // console.log("定时......",timer_list)
        // console.log("年:", fullYear)
        // console.log("月:", month)
        // console.log("日:", dat)
        // console.log("时:", hours)
        // console.log("分:", minutes)
        // console.log("秒:", seconds)

        for (let i in timer_list) {
            let item = timer_list[i]

            if (item.year != "*" && item.year != fullYear) {
                continue
            }
            if (item.month != "*" && item.month != month) {
                continue
            }
            if (item.date != "*" && item.date != dat) {
                continue
            }
            if (item.hours != "*" && item.hours != hours) {
                continue
            }
            if (item.minutes != "*" && item.minutes != minutes) {
                continue
            }
            if (item.seconds != "*" && item.seconds != seconds) {
                continue
            }
            console.log("调用定时任务", item)
            if (item.func && item.parm) {
                item.func(item.parm)
            } else {
                item.func()
            }
        }
    }, 1000)
}

总结

到此这篇关于JavaScript实现手写原生任务定时器的文章就介绍到这了,更多相关JavaScript任务定时器内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章