Make a mock task manager in vanilla javascript

I am practicing coding questions, and I am not able to solve this one, I need help. Basically let only 2 task setTimeouts run at a time. Can someone nudge me in the right direction? How do I detect when a setTimeout is done? Thanks in advance!

var tm = new TaskManager(2);
tm.runTask("one", 200);
tm.runTask("two", 300);
tm.runTask("three", 1000);


class TaskManager {
    constructor(maxTaskAllowed) {
    }
    runTask(taskName, duration) {
        setTimeout(function() {
            console.log("Task " + taskName + " is done.");
        }, duration);
        
    }
}

2 answers

  • answered 2018-02-13 01:53 Occam's Razor

    you could use a counter to keep track of how many are running at once.. you could implement something like this....

    class myclass{
    
        constructor(){ 
            // count the number of pending tasks
            this.counter = 0 
        }
        
        do_a_thing(){
          if(this.counter >= 2){ 
            // if there's more that one task pending
            // dont do anything
            return console.log("nope nope nope");
          }
          // add one to indicate another task is ending
          this.counter++;
          setTimeout(()=>{
            // task is done subtract one from the counter
            this.counter--;
            console.log("did a thing");
          });
        }
    }
    
    var m = new myclass();
    m.do_a_thing();
    m.do_a_thing();
    m.do_a_thing();
    m.do_a_thing();
    m.do_a_thing();
    m.do_a_thing();

  • answered 2018-02-13 02:13 Lex

    Can someone nudge me in the right direction? How do I detect when a setTimeout is done?

    Actually... your code works! When you see the message printed by "console.log("Task " + taskName + " is done.");" the setTimeout has finished.

        class TaskManager {
            constructor(maxTaskAllowed) {
            }
            runTask(taskName, duration) {
                setTimeout(function() {
                    console.log("Task " + taskName + " is done.");
                }, duration);
                
            }
        }
        
        var tm = new TaskManager(2);
        tm.runTask("one", 200); tm.runTask("two", 300); tm.runTask("three", 1000);