Search code examples
jqueryfunctiontimercall

how can call function multiple times with different values in jquery


I have a function that i want call it two or there times at same time with diffrent values for example:

var stopClock = false;

function myTimer(clockTime, inClockFunction) {

    stopClock = false;
    ChatClock = {
        totalSeconds: 0,
        start: function () {
            this.interval = setInterval(function () {
                if (!stopClock) {
                    inClockFunction()
                }
                else {
                    ChatClock.pause();
                }
            }, clockTime);
        },
        pause: function () {
            clearInterval(this.interval);
            delete this.interval;
        }
    };  
    ChatClock.start();  
}

var time1 = 5000;
var func1 = function() {
   alert(time1)
   stopClock = true;
}
myTimer(5000, func1 )

var time2 = 8000;
var func2 = function() {
    alert(time2)
}
myTimer(8000, func2 )

func2 will not show alert because stopClock variable changed to true in func1, how can call multiple times with different values?


Solution

  • You variable stopClock is global, so both functions access same variable value. Initialize variable only inside function and you should be fine. Here is jsFiddle for you.

    Your javascript has more public/private variables & functions conflicts. Here's another jsFiddle with all of them(necessary for code to function) fixed.

    var timeris = function myTimer(clockTime, inClockFunction) {
    
        var stopClock = false;
        var ChatClock = {
            totalSeconds: 0,
            start: function () {
                this.interval = setInterval(function () {
                    if (!stopClock) {
                        stopClock = inClockFunction();
                    }
                    else {
                        ChatClock.pause();
                    }
                }, clockTime);
            },
            pause: function () {
                clearInterval(this.interval);
                delete this.interval;
            }
        };  
        ChatClock.start();  
    }
    
    var time1 = 5000;
    var func1 = function() {
       alert(time1);
       return true;
    }
    aa = new timeris(5000, func1 );
    
    var time2 = 8000;
    var func2 = function() {
        alert(time2);
        return false;
    }
    bb = new timeris(8000, func2 );