Stop setInterval call in JavaScript

前端 未结 16 1878
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  猫巷女王i
    2020-11-21 05:42

    Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).

    // Timer with 1000ms (1 second) base interval resolution.
    const timer = new TaskTimer(1000);
    
    // Add task(s) based on tick intervals.
    timer.add({
        id: 'job1',         // unique id of the task
        tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
        totalRuns: 10,      // run 10 times only. (omit for unlimited times)
        callback(task) {
            // code to be executed on each run
            console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
            // stop the timer anytime you like
            if (someCondition()) timer.stop();
            // or simply remove this task if you have others
            if (someCondition()) timer.remove(task.id);
        }
    });
    
    // Start the timer
    timer.start();
    

    In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

    See more here.

提交回复
热议问题