Skip to content Skip to sidebar Skip to footer

Pause & Resume Settimeout In A Loop

I have the following $.each which loops through an object. Every 5 seconds the get_file() function is called. Is there anyway to include a Pause and Resume option. So that if I c

Solution 1:

Make an array of all the timers, so you can clear them when the pause button is clicked. Use a global variable to keep track of how far you are through the list of files to load. Then you can resume from where you left off.

var curfile = 0;
var load_file_timers;

functionload_files() {
    load_file_timers = obj.map(function(v, i) {
        if (i < curfile) {
            returnnull;
        } else {
            returnsetTimeout(function() {
                var file = v.newfile;
                var timeline_date = moment(v.last_modified_date).format("dddd, MMMM Do YYYY, h:mm:ss a");
                bHover = 0; //re-highlight links
                $(".timeline_msg").html(timeline_date);
                get_file(file);
                curfile++;
            }, 5000 * (i - curfile + 1));
        }
    });
}

load_files();

$("#pause").click(function() {
    $.each(load_file_timers, function(i, timer) {
        if (timer) {
            clearTimeout(timer);
        }
    });
});

$("#resume").click(load_files);

Solution 2:

When you call setTimeout() you are returned a handle to that timer which can then be passed to a call to clearTimeout(). This will cancel the subsequent firing of the timer (assuming it hasn't already fired). This can be code associated with a "Pause" option. When you want to resume, you could simply execute the same setTimeout() code again to resume the timer for the next interval.

This story presumes that a timer has been setup with setTimeout() and that a pause should prevent the timer from firing.

See setTimeout.

Solution 3:

A recursive solution for this is,

var array = $.map(obj,function(v,i){
    return v;
});

var timer;
var fileId=0;

functionexecute(){
     timer = setTimeout(function () {
               v = array[fileId];
               var file = v.newfile;
               var timeline_date = moment(v.last_modified_date).format("dddd, MMMM Do YYYY, h:mm:ss a");
               bHover = 0; //re-highlight links
               $(".timeline_msg").html(timeline_date);
               get_file(file);
               fileId++;
               if (array.length > fileId){
                   execute();
               }
           }, 1000);
}

$('document').ready(function(){

    $('#loop_controler').click(function(){
        if (fileId < array.length){
            if ($(this).text() == 'pause'){
              clearTimeout(timer);
              $(this).text('resume');
            } else {
              execute();
              $(this).text('pause');
            }
        }
    });

    execute(array,0);
});

Post a Comment for "Pause & Resume Settimeout In A Loop"