JSFiddle - React, Tailwind, and code Playground

by Marcus Ekwall

HTML

<button id="toggle">Start</button>
<div id="mouse"></div>

JavaScript

var stopMove = {
    event: null,
    interval: null,
    coords: { y: 0, x: 0},
    stopped: true,
    init: function(options) {
        var self = this;
        $(document).mousemove(function(e){
            self.event=e;
            if (self.coords.y == e.pageY && self.coords.x == e.pageX) {
                self.stopped = true;
                return;
            }
            self.stopped=false;
            self.coords.y = e.pageY;
            self.coords.x = e.pageX;
            
        });
        this.interval = setInterval(function(){
            return self.stopped ? options.stop(self.event) : options.move(self.event);
        }, options.duration);
        return this;
    },
    stop: function(){
        $(document).unbind("mousemove", this.event)
        clearInterval(this.interval);
    },
};

// function to pass
var onMove = function(event){
    $("#mouse").text("Y: "+event.pageY+" X: "+event.pageX);
};

var onStop = function(event){
    $("#mouse").text("Stopped!");
};

$("button").toggle(function(){
    stopMove.init({
        move: onMove,
        stop: onStop,
        duration: 50
    });
    $(this).text("Stop");
}, function(){
    stopMove.stop();
    $(this).text("Start");
});