简体   繁体   中英

How would I go about using window.find() activate on that text only once

I use hack.chat a bit, and I saw that they have a bot, but the bot program wasn't working for me so I decided to make my own.

var finderBinder;
var searchFor = function(command){
    finderBinder = window.find(command, true, true);
    if(finderBinder){
        if(command === "/hello"){
            ws.send(JSON.stringify({cmd: "chat", text: "hello!"}));
        }
        else if(command === "/cry"){
            ws.send(JSON.stringify({cmd: "chat", text: "wah waha wahhh"}));
        }
        else
        {
            console.log("it was found but it was not a command.")
        }
    }
    else
    {
        console.log("Did not find the command");
    }
}

var loopdeloop = 0;

while(loopdeloop === 0){
    searchFor("/hello");
    searchFor("/cry");
}

Now, the first part works if I just run that by itself on the page, and enter searchFor("/hello"); that would work, but if I wanted it to just automatically do that whenever a message popped up, I attempted the loop,(In a empty chatroom so it wouldn't spam a used room if it did) and it crashed my browser. I know why it did that. because it just checked forever, and it saw it forever so it kept on trying to do the code forever..

But how would I make it only run the searchFor when a new text showed up so it would run the text in it and if it was a command it would do the command? Or is there a better way to do this?

The simplest way to stop your function from looping to infinity (and beyond!) would be to call it once every X seconds/minutes/hours/lightyears.

Using setInterval(searchFor, 1000); where the second parameter is the time interval in milliseconds.

To pass a parameter to your searchFor function, you must create an anonymous function so it doesn't get called right away.

setInterval( function() { searchFor ("/hello"); }, 1000 );

This will call your function every ~1 second, although keep in mind there is some overhead to javascript and there will be a slight delay. Also be careful of looping your function too often, as it will be expensive, and browsers have a built in delay, for example, you will not be able to setInterval to 2 ms and have it function normally cross browser.

Edit: The more elegant solution of binding an event to a change in the textbox is also possible, depending on how the page is setup and your access to it, hard to answer without that structure known.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM